mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-01 04:38:44 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63590ede60 |
No files matched your search
@@ -7,9 +7,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
#### 7.x Releases
|
||||
|
||||
- `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)
|
||||
@@ -138,42 +135,6 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
|
||||
- **New**: Add the MIN and MAX multi-argument SQL functions to the query interface by [@groue](https://github.com/groue) in [#1745](https://github.com/groue/GRDB.swift/pull/1745)
|
||||
- **Fixed**: Transaction observers are not impacted by Task Cancellation by [@groue](https://github.com/groue) in [#1747](https://github.com/groue/GRDB.swift/pull/1747). This fixes unexpected `ValueObservation` failures in applications that perform asynchronous writes.
|
||||
|
||||
## 7.3.0
|
||||
|
||||
Released February 23, 2025
|
||||
|
||||
+113
-129
@@ -58,26 +58,15 @@ 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: Codable, Identifiable, FetchableRecord, PersistableRecord {
|
||||
struct Author {
|
||||
var id: Int64
|
||||
var name: String
|
||||
|
||||
enum Columns {
|
||||
static let id = Column(CodingKeys.id)
|
||||
static let name = Column(CodingKeys.name)
|
||||
}
|
||||
}
|
||||
|
||||
struct Book: Codable, Identifiable, FetchableRecord, PersistableRecord {
|
||||
struct Book {
|
||||
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)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -86,7 +75,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 { $0.authorId == author.id }
|
||||
.filter(Column("authorId") == author.id)
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
@@ -132,7 +121,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: Decodable, FetchableRecord {
|
||||
struct BookInfo: FetchableRecord, Decodable {
|
||||
let book: Book
|
||||
let author: Author?
|
||||
}
|
||||
@@ -739,15 +728,9 @@ 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([Columns.authorId])
|
||||
static let translatorForeignKey = ForeignKey([Columns.translatorId])
|
||||
static let authorForeignKey = ForeignKey(["authorId"])
|
||||
static let translatorForeignKey = ForeignKey(["translatorId"])
|
||||
|
||||
// Use foreign keys to define associations:
|
||||
static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
@@ -764,11 +747,24 @@ 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([Columns.authorId], to: [Person.Columns.id])
|
||||
static let authorForeignKey = ForeignKey(["authorId"], to: ["id"])
|
||||
static let author = belongsTo(Person.self, using: authorForeignKey)
|
||||
}
|
||||
```
|
||||
@@ -840,8 +836,8 @@ Requests for associated records can be filtered and ordered like all [query inte
|
||||
```swift
|
||||
let novels = try author
|
||||
.books
|
||||
.filter { $0.kind == BookKind.novel }
|
||||
.order(\.publishDate.desc)
|
||||
.filter(Column("kind") == BookKind.novel)
|
||||
.order(Column("publishDate").desc)
|
||||
.fetchAll(db) // [Book]
|
||||
```
|
||||
|
||||
@@ -925,7 +921,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var author: PartialAuthor
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.including(required: Book.author.select { [$0.name, $0.country] })
|
||||
.including(required: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -939,7 +935,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var country: String
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select(\.country)
|
||||
.annotated(withRequired: Book.author.select(Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -986,7 +982,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var author: PartialAuthor?
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.including(optional: Book.author.select { [$0.name, $0.country] })
|
||||
.including(optional: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1000,7 +996,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var country: String?
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select(\.country))
|
||||
.annotated(withOptional: Book.author.select(Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1068,7 +1064,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
var books: [PartialBook]
|
||||
}
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books.select { [$0.title, $0.year] })
|
||||
.including(all: Author.books.select(Column("title"), Column("year")))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1083,7 +1079,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
}
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books
|
||||
.select(\.title)
|
||||
.select(Column("title"))
|
||||
.forKey("bookTitles"))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
@@ -1097,7 +1093,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 { [$0.name, $0.country] })
|
||||
let request = Book.annotated(withRequired: Book.author.select(Column("name"), Column("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".
|
||||
@@ -1112,7 +1108,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var country: String // A column of the required associated record
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select { [$0.name, $0.country] })
|
||||
.annotated(withRequired: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1126,7 +1122,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var authorName: String
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select { $0.name.forKey("authorName") })
|
||||
.annotated(withRequired: Book.author.select(Column("name").forKey("authorName")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1139,7 +1135,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 { [$0.name, $0.country] })
|
||||
let request = Book.annotated(withOptional: Book.author.select(Column("name"), Column("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".
|
||||
@@ -1154,7 +1150,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var country: String? // A column of the optional associated record
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select { [$0.name, $0.country] })
|
||||
.annotated(withOptional: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1168,7 +1164,7 @@ struct BookInfo: Decodable, FetchableRecord {
|
||||
var authorName: String?
|
||||
}
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select { $0.name.forKey("authorName") })
|
||||
.annotated(withOptional: Book.author.select(Column("name").forKey("authorName")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1182,7 +1178,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 { $0.country == "France" })
|
||||
let request = Book.joining(required: Book.author.filter(Column("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".
|
||||
@@ -1192,7 +1188,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 { $0.country == "France" })
|
||||
.joining(required: Book.author.filter(Column("country") == "France"))
|
||||
.fetchAll(db)
|
||||
```
|
||||
|
||||
@@ -1243,7 +1239,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.including(required: Book.author.select { [$0.name, $0.country] })
|
||||
.including(required: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1258,9 +1254,9 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.annotated(withRequired: Book.author.select {
|
||||
[$0.name.forKey("authorName"), $0.country]
|
||||
})
|
||||
.annotated(withRequired: Book.author.select(
|
||||
Column("name").forKey("authorName"),
|
||||
Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1290,7 +1286,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.including(optional: Book.author.select { [$0.name, $0.country] })
|
||||
.including(optional: Book.author.select(Column("name"), Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1305,9 +1301,9 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let bookInfos = try Book
|
||||
.annotated(withOptional: Book.author.select {
|
||||
[$0.name.forKey("authorName"), $0.country]
|
||||
})
|
||||
.annotated(withOptional: Book.author.select(
|
||||
Column("name").forKey("authorName"),
|
||||
Column("country")))
|
||||
.asRequest(of: BookInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1337,7 +1333,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
}
|
||||
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books.select { [$0.title, $0.year] })
|
||||
.including(all: Author.books.select(Column("title"), Column("year")))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1350,7 +1346,7 @@ In this chapter, we take the reversed perspective. We list various shapes of dec
|
||||
|
||||
let authorInfos = try Author
|
||||
.including(all: Author.books
|
||||
.select(\.title)
|
||||
.select(Column("title"))
|
||||
.forKey("bookTitles"))
|
||||
.asRequest(of: AuthorInfo.self)
|
||||
.fetchAll(db)
|
||||
@@ -1464,7 +1460,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 { $0.countryCode == "FR" }
|
||||
let frenchAuthor = Book.author.filter(Column("countryCode") == "FR")
|
||||
let request = Book.joining(required: frenchAuthor)
|
||||
|
||||
// This request feeds the Book record:
|
||||
@@ -1478,10 +1474,10 @@ The one below fetches all authors along with their novels and poems:
|
||||
```swift
|
||||
let request = Author
|
||||
.including(all: Author.book
|
||||
.filter { $0.kind == "novel" }
|
||||
.filter(Column("kind") == "novel")
|
||||
.forKey("novels"))
|
||||
.including(all: Author.book
|
||||
.filter { $0.kind == "poems" }
|
||||
.filter(Column("kind") == "poems")
|
||||
.forKey("poems"))
|
||||
|
||||
// This request can feed the following record:
|
||||
@@ -1512,7 +1508,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(\.name)
|
||||
let sortedAuthor = Book.author.order(Column("name"))
|
||||
let request = Book.including(required: sortedAuthor)
|
||||
```
|
||||
|
||||
@@ -1523,10 +1519,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(\.name)
|
||||
let sortedAuthor = Book.author.order(Column("name"))
|
||||
let request = Book
|
||||
.including(required: sortedAuthor)
|
||||
.order(\.publishDate.desc)
|
||||
.order(Column("publishDate").desc)
|
||||
```
|
||||
|
||||
**There are more sorting options:**
|
||||
@@ -1563,7 +1559,7 @@ The `Team.players` association is ordered by position, so that all team players
|
||||
|
||||
```swift
|
||||
extension Team {
|
||||
static let players = hasMany(Player.self).order(\.position)
|
||||
static let players = hasMany(Player.self).order(Column("position"))
|
||||
|
||||
var players: QueryInterfaceRequest<Player> {
|
||||
request(for: Team.players)
|
||||
@@ -1595,7 +1591,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(\.position)
|
||||
static let playerRoles = hasMany(PlayerRole.self).order(Column("position"))
|
||||
|
||||
static let players = hasMany(Player.self, through: playerRoles, using: PlayerRole.player)
|
||||
|
||||
@@ -1627,9 +1623,9 @@ let teamInfos = try Team
|
||||
|
||||
// Custom ordering
|
||||
let team: Team = ...
|
||||
let players = try team.players.order(\.name).fetchAll(db)
|
||||
let players = try team.players.order(Column("name")).fetchAll(db)
|
||||
let teamInfos = try Team
|
||||
.including(all: Team.players.order(\.name))
|
||||
.including(all: Team.players.order(Column("name")))
|
||||
.asRequest(of: TeamInfo.self)
|
||||
.fetchAll(db)
|
||||
```
|
||||
@@ -1655,7 +1651,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 { [$0.id, $0.name] }
|
||||
let restrictedAuthor = Book.author.select(Column("id"), Column("name"))
|
||||
let request = Book.including(required: restrictedAuthor)
|
||||
```
|
||||
|
||||
@@ -1677,7 +1673,7 @@ Associations support more refinements:
|
||||
}
|
||||
|
||||
let distinctBookKinds = Author.books
|
||||
.select(\.kind)
|
||||
.select(Column("kind"))
|
||||
.distinct()
|
||||
.forKey("bookKinds")
|
||||
|
||||
@@ -1703,8 +1699,10 @@ Associations support more refinements:
|
||||
}
|
||||
|
||||
let bookKindInfos = Author.books
|
||||
.select { [$0.kind, max($0.year).forKey("maxYear")] }
|
||||
.group(\.kind)
|
||||
.select(
|
||||
Column("kind"),
|
||||
max(Column("year")).forKey("maxYear"))
|
||||
.group(Column("kind"))
|
||||
.forKey("bookKindInfos")
|
||||
|
||||
let authorInfos: [AuthorInfo] = try Author
|
||||
@@ -1774,7 +1772,7 @@ Let's first see a wrong way to do it:
|
||||
// WHERE book.publishDate >= book.deathDate
|
||||
let request = Book
|
||||
.joining(required: Book.author)
|
||||
.filter { $0.publishDate >= $0.deathDate }
|
||||
.filter(Column("publishDate") >= Column("deathDate"))
|
||||
```
|
||||
|
||||
When executed, we'll get a DatabaseError of code 1, "no such column: book.deathDate".
|
||||
@@ -1784,35 +1782,21 @@ 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<Author>()
|
||||
let authorAlias = TableAlias()
|
||||
```
|
||||
|
||||
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
|
||||
// Swift 6.1
|
||||
//
|
||||
// > SELECT book.*
|
||||
// > FROM book
|
||||
// > JOIN person ON person.id = book.authorId
|
||||
// > WHERE book.publishDate >= person.deathDate
|
||||
// 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.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] }
|
||||
.filter(Column("publishDate") >= authorAlias[Column("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
|
||||
@@ -1822,7 +1806,7 @@ Note that Swift 6.1 is required for the short syntac `alias.column`. From now on
|
||||
// ORDER BY person.name, book.publishDate
|
||||
let request = Book
|
||||
.joining(required: Book.author.aliased(authorAlias))
|
||||
.order { [authorAlias.name, $0.publishDate] }
|
||||
.order(authorAlias[Column("name")], Column("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:
|
||||
@@ -1833,8 +1817,8 @@ let request = Book
|
||||
// JOIN person a ON a.id = b.authorId
|
||||
// AND a.countryCode = 'FR'
|
||||
// WHERE b.publishDate >= a.deathDate
|
||||
let bookAlias = TableAlias<Book>(name: "b")
|
||||
let authorAlias = TableAlias<Person>(name: "a")
|
||||
let bookAlias = TableAlias(name: "b")
|
||||
let authorAlias = TableAlias(name: "a")
|
||||
let request = Book.aliased(bookAlias)
|
||||
.joining(required: Book.author.aliased(authorAlias)
|
||||
.filter(sql: "a.countryCode = ?", arguments: ["FR"]))
|
||||
@@ -1854,11 +1838,11 @@ let request = Book.aliased(bookAlias)
|
||||
>
|
||||
> ```swift
|
||||
> // NOT IMPLEMENTED: loading all authors along with their posthumous books
|
||||
> let authorAlias = TableAlias<Author>()
|
||||
> let authorAlias = TableAlias()
|
||||
> let request = Author
|
||||
> .aliased(authorAlias)
|
||||
> .including(all: Author.books
|
||||
> .filter { $0.publishDate >= authorAlias.deathDate })
|
||||
> .filter(Column("publishDate") >= authorAlias[Column("deathDate")]))
|
||||
> ```
|
||||
|
||||
|
||||
@@ -1920,7 +1904,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 { $0.country == country }
|
||||
filter(Column("country") == country)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1933,13 +1917,12 @@ extension DerivableRequest<Book> {
|
||||
|
||||
/// Order books by author name and then book title
|
||||
func orderedByAuthorNameAndYear() -> Self {
|
||||
let authorAlias = TableAlias<Author>()
|
||||
let authorAlias = TableAlias()
|
||||
return self
|
||||
.joining(optional: Book.author.aliased(authorAlias))
|
||||
.order { [
|
||||
authorAlias.name.collating(.localizedCaseInsensitiveCompare),
|
||||
$0.year,
|
||||
] }
|
||||
.order(
|
||||
authorAlias[Column("name")].collating(.localizedCaseInsensitiveCompare),
|
||||
Column("year"))
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -2080,7 +2063,7 @@ Keys can also be customized with the `forKey` method:
|
||||
```swift
|
||||
extension Author {
|
||||
static let novels = books
|
||||
.filter { $0.kind == "novel" }
|
||||
.filter(Column("kind") == "novel")
|
||||
.forKey("novels")
|
||||
}
|
||||
Author.including(all: Author.novels) // association key "novels"
|
||||
@@ -2186,25 +2169,26 @@ struct BookInfo: FetchableRecord {
|
||||
|
||||
init(row: Row) throws {
|
||||
book = try Book(row: row)
|
||||
author = try row.decode(forKey: "author")
|
||||
country = try row.decodeIfPresent(forKey: "country")
|
||||
coverImage = try row.decodeIfPresent(forKey: "coverImage")
|
||||
author = row["author"]
|
||||
country = row["country"]
|
||||
coverImage = row["coverImage"]
|
||||
}
|
||||
}
|
||||
|
||||
let bookInfos: [BookInfo] = try BookInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
When you extract a record from a row, GRDB looks up the tree of **association keys**:
|
||||
You are already familiar with row subscripts to decode [database values](../README.md#column-values):
|
||||
|
||||
```swift
|
||||
let author = try row.decode(Author.self, forKey: "author")
|
||||
let name: String = row["name"]
|
||||
```
|
||||
|
||||
If the key is not found, or only associated with columns that are all NULL, an optional record is decoded as nil:
|
||||
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:
|
||||
|
||||
```swift
|
||||
let country = try row.decodeIfPresent(Country.self, forKey: "country")
|
||||
let author: Author = row["author"]
|
||||
let country: Country? = row["country"]
|
||||
```
|
||||
|
||||
You can also perform custom navigation in the tree by using *row scopes*. See [Row Adapters] for more information.
|
||||
@@ -2220,7 +2204,7 @@ struct AuthorInfo: FetchableRecord {
|
||||
|
||||
init(row: Row) throws {
|
||||
author = try Author(row: row)
|
||||
books = try row.decode(forKey: "books")
|
||||
books = row["books"]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2304,7 +2288,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($0.year) }
|
||||
let request = author.books.select(max(yearColumn))
|
||||
let maxBookYear = try Int.fetchOne(db, request) // Int?
|
||||
```
|
||||
|
||||
@@ -2375,7 +2359,7 @@ struct AuthorInfo: Decodable, FetchableRecord {
|
||||
// GROUP BY author.id
|
||||
let request = Author.annotated(with:
|
||||
Author.books.count,
|
||||
Author.books.max(\.year))
|
||||
Author.books.max(Column("year")))
|
||||
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
|
||||
@@ -2392,13 +2376,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(\.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` ¹ |
|
||||
| `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` ¹ |
|
||||
|
||||
¹ 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.
|
||||
|
||||
@@ -2527,7 +2511,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let request = Author.having(Author.books.max(\.year) >= 2010)
|
||||
let request = Author.having(Author.books.max(Column("year")) >= 2010)
|
||||
```
|
||||
|
||||
- Authors who wrote at least one book of kind "novel":
|
||||
@@ -2546,7 +2530,7 @@ The `having(_:)` method filters a request according to an aggregated value. You
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let novels = Author.books.filter { $0.kind == "novel" }
|
||||
let novels = Author.books.filter(Column("kind") == "novel")
|
||||
let request = Author.having(novels.isEmpty == false)
|
||||
```
|
||||
|
||||
@@ -2632,7 +2616,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let request = Author.having(Author.books.max(\.year) >= 2010)
|
||||
let request = Author.having(Author.books.max(Column("year")) >= 2010)
|
||||
```
|
||||
|
||||
- Arithmetic operators `+`, `-`, `*`, `/`
|
||||
@@ -2672,7 +2656,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let request = Team.annotated(with: Team.players.min(\.score) ?? 0)
|
||||
let request = Team.annotated(with: Team.players.min(Column("score")) ?? 0)
|
||||
```
|
||||
|
||||
- SQL functions `ABS`, `CAST`, and `LENGTH` are available as the `abs`, `cast`, and `length` Swift functions:
|
||||
@@ -2690,7 +2674,7 @@ Aggregates can be modified and combined with Swift operators:
|
||||
</details>
|
||||
|
||||
```swift
|
||||
let request = Team.annotated(with: abs(Team.players.max(\.score)))
|
||||
let request = Team.annotated(with: abs(Team.players.max(Column("score"))))
|
||||
```
|
||||
|
||||
### Isolation of Multiple Aggregates
|
||||
@@ -2727,8 +2711,8 @@ In the example below, we use compute two aggregates from the same association `A
|
||||
}
|
||||
|
||||
let request = Author.annotated(with:
|
||||
Author.books.min(\.year), // association key "books"
|
||||
Author.books.max(\.year)) // association key "books"
|
||||
Author.books.min(Column("year")), // association key "books"
|
||||
Author.books.max(Column("year"))) // association key "books"
|
||||
let authorInfos: [AuthorInfo] = try AuthorInfo.fetchAll(db, request)
|
||||
```
|
||||
|
||||
@@ -2798,11 +2782,11 @@ But in the following example, we use the same association `Author.books` twice,
|
||||
}
|
||||
|
||||
let novelCount = Author.books
|
||||
.filter { $0.kind == "novel" }
|
||||
.filter(Column("kind") == "novel")
|
||||
.forKey("novels") // association key "novels"
|
||||
.count
|
||||
let theatrePlayCount = Author.books
|
||||
.filter { $0.kind == "theatrePlay" }
|
||||
.filter(Column("kind") == "theatrePlay")
|
||||
.forKey("theatrePlays") // association key "theatrePlays"
|
||||
.count
|
||||
let request = Author.annotated(with: novelCount, theatrePlayCount)
|
||||
@@ -2829,11 +2813,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 { $0.kind == "novel" }
|
||||
.filter(Column("kind") == "novel")
|
||||
.count
|
||||
.forKey("novelCount")
|
||||
let theatrePlayCount = Author.books // association key "books"
|
||||
.filter { $0.kind == "theatrePlay" }
|
||||
.filter(Column("kind") == "theatrePlay")
|
||||
.count
|
||||
.forKey("theatrePlayCount")
|
||||
let request = Author.annotated(with: novelCount, theatrePlayCount)
|
||||
@@ -2863,11 +2847,11 @@ Those methods are defined on extensions to the `DerivableRequest` protocol:
|
||||
```swift
|
||||
extension DerivableRequest<Author> {
|
||||
func filter(country: String) -> Self {
|
||||
filter { $0.country == country }
|
||||
filter(Column("country") == country)
|
||||
}
|
||||
|
||||
func orderedByName() -> Self {
|
||||
order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
order(Column("name").collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2898,11 +2882,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<Author>()
|
||||
let authorAlias = TableAlias()
|
||||
let request = Author
|
||||
.aliased(authorAlias)
|
||||
.including(all: Author.books
|
||||
.filter { $0.publishDate >= authorAlias.deathDate })
|
||||
.filter(Column("publishDate") >= authorAlias[Column("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(\.score.desc)
|
||||
.order(Column("score").desc)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
@@ -358,7 +358,7 @@ let totalPlayerCountPublisher = ValueObservation
|
||||
// OK
|
||||
let bestPlayerPublisher = ValueObservation
|
||||
.tracking(Player
|
||||
.order(\.score.desc)
|
||||
.order(Column("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(\.name))
|
||||
request: Player.select(Column("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 { $0.name == playerNameCTE.all() }
|
||||
.filter(Column("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) { $0.name.set(to: playerNameCTE.all()) }
|
||||
.updateAll(db, Column("name").set(to: playerNameCTE.all()))
|
||||
|
||||
// WITH playerName AS (SELECT 'O''Brien')
|
||||
// DELETE FROM player WHERE name = (SELECT * FROM playerName)
|
||||
try Player
|
||||
.with(playerNameCTE)
|
||||
.filter { $0.name == playerNameCTE.all() }
|
||||
.filter(Column("name") == playerNameCTE.all())
|
||||
.deleteAll(db)
|
||||
```
|
||||
|
||||
@@ -281,15 +281,9 @@ 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")
|
||||
...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -321,8 +315,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 { max($0.date) }
|
||||
.group(\.chatId)
|
||||
.annotated(with: max(Column("date")))
|
||||
.group(Column("chatID"))
|
||||
```
|
||||
|
||||
We can now define the CTE for the latest messages:
|
||||
@@ -330,7 +324,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<Message>(
|
||||
let latestMessageCTE = CommonTableExpression(
|
||||
named: "latestMessage",
|
||||
request: latestMessageRequest)
|
||||
```
|
||||
@@ -343,9 +337,9 @@ The association from a chat to its latest message follows:
|
||||
let latestMessage = Chat.association(
|
||||
to: latestMessageCTE,
|
||||
on: { chat, latestMessage in
|
||||
chat.id == latestMessage.chatId
|
||||
chat[Column("id")] == latestMessage[Column("chatID")]
|
||||
})
|
||||
.order(\.date.desc)
|
||||
.order(Column("date").desc)
|
||||
```
|
||||
|
||||
The final request can now be defined:
|
||||
|
||||
@@ -9,20 +9,18 @@ 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.
|
||||
@@ -30,31 +28,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
|
||||
@@ -63,52 +61,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.
|
||||
@@ -118,21 +116,17 @@ 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
|
||||
|
||||
@@ -12,7 +12,7 @@ import os.log
|
||||
/// let dbQueue = try DatabaseQueue(configuration: config)
|
||||
/// let appDatabase = try AppDatabase(dbQueue)
|
||||
/// ```
|
||||
struct AppDatabase: Sendable {
|
||||
final class 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 { db in
|
||||
try await dbWriter.write { [self] db in
|
||||
if try Player.all().isEmpty(db) {
|
||||
// When database is empty, insert new random players
|
||||
try createRandomPlayers(db)
|
||||
|
||||
@@ -64,3 +64,45 @@ 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,16 +41,9 @@ import GRDB
|
||||
let observation = ValueObservation.tracking { [ordering] db in
|
||||
switch ordering {
|
||||
case .byName:
|
||||
try Player
|
||||
.order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
.fetchAll(db)
|
||||
try Player.all().orderedByName().fetchAll(db)
|
||||
case .byScore:
|
||||
try Player
|
||||
.order { [
|
||||
$0.score.desc,
|
||||
$0.name.collating(.localizedCaseInsensitiveCompare),
|
||||
] }
|
||||
.fetchAll(db)
|
||||
try Player.all().orderedByScore().fetchAll(db)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 { $0.content.match(pattern) }.fetchAll(db)
|
||||
let documents = try Document.filter(Column("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 { $0.content.match(pattern) }.fetchAll(db)
|
||||
let documents = try Document.filter(Column("content").match(pattern)).fetchAll(db)
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -32,14 +32,14 @@ try dbQueue.inDatabase { db in
|
||||
CREATE TABLE place (
|
||||
id INTEGER PRIMARY KEY,
|
||||
title TEXT,
|
||||
isFavorite BOOLEAN NOT NULL,
|
||||
favorite BOOLEAN NOT NULL,
|
||||
latitude DOUBLE NOT NULL,
|
||||
longitude DOUBLE NOT NULL
|
||||
)
|
||||
""")
|
||||
|
||||
try db.execute(sql: """
|
||||
INSERT INTO place (title, isFavorite, latitude, longitude)
|
||||
INSERT INTO place (title, favorite, 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 isFavorite: Bool = row["isFavorite"]
|
||||
let favorite: Bool = row["favorite"]
|
||||
let coordinate = CLLocationCoordinate2D(
|
||||
latitude: row["latitude"],
|
||||
longitude: row["longitude"])
|
||||
print("Fetched", title, isFavorite, coordinate)
|
||||
print("Fetched", title, favorite, coordinate)
|
||||
}
|
||||
|
||||
let placeCount = try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM place")! // Int
|
||||
@@ -69,43 +69,35 @@ try! dbQueue.inDatabase { db in
|
||||
struct Place {
|
||||
var id: Int64?
|
||||
var title: String?
|
||||
var isFavorite: Bool
|
||||
var favorite: Bool
|
||||
var coordinate: CLLocationCoordinate2D
|
||||
}
|
||||
|
||||
// Adopt FetchableRecord
|
||||
extension Place : FetchableRecord {
|
||||
init(row: Row) {
|
||||
id = row[Columns.id]
|
||||
title = row[Columns.title]
|
||||
isFavorite = row[Columns.isFavorite]
|
||||
id = row["id"]
|
||||
title = row["title"]
|
||||
favorite = row["favorite"]
|
||||
coordinate = CLLocationCoordinate2DMake(
|
||||
row[Columns.latitude],
|
||||
row[Columns.longitude])
|
||||
row["latitude"],
|
||||
row["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[Columns.id] = id
|
||||
container[Columns.title] = title
|
||||
container[Columns.isFavorite] = isFavorite
|
||||
container[Columns.latitude] = coordinate.latitude
|
||||
container[Columns.longitude] = coordinate.longitude
|
||||
container["id"] = id
|
||||
container["title"] = title
|
||||
container["favorite"] = favorite
|
||||
container["latitude"] = coordinate.latitude
|
||||
container["longitude"] = coordinate.longitude
|
||||
}
|
||||
|
||||
mutating func didInsert(_ inserted: InsertionSuccess) {
|
||||
@@ -117,13 +109,13 @@ try dbQueue.inDatabase { db in
|
||||
var berlin = Place(
|
||||
id: nil,
|
||||
title: "Berlin",
|
||||
isFavorite: false,
|
||||
favorite: false,
|
||||
coordinate: CLLocationCoordinate2DMake(52.52437, 13.41053))
|
||||
|
||||
try berlin.insert(db)
|
||||
berlin.id // some value
|
||||
|
||||
berlin.isFavorite = true
|
||||
berlin.favorite = true
|
||||
try berlin.update(db)
|
||||
|
||||
// Fetch from SQL
|
||||
@@ -132,10 +124,13 @@ try dbQueue.inDatabase { db in
|
||||
|
||||
//: Avoid SQL with the query interface:
|
||||
|
||||
berlin = try Place.filter { $0.title == "Berlin" }.fetchOne(db)! // Place
|
||||
let title = Column("title")
|
||||
let favorite = Column("favorite")
|
||||
|
||||
berlin = try Place.filter(title == "Berlin").fetchOne(db)! // Place
|
||||
let paris = try Place.fetchOne(db, key: 1) // Place?
|
||||
let favoritePlaces = try Place // [Place]
|
||||
.filter { $0.isFavorite == true }
|
||||
.order { $0.title }
|
||||
.filter(favorite == true)
|
||||
.order(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 { $0.id == 1 }.fetchOne(db)
|
||||
try Player.filter(Column("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 { $0.id == 1 }.fetchOne(db)
|
||||
try Player.filter(Column("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 { $0.name == "O'Brien" }
|
||||
Player.filter(Column("name") == "O'Brien")
|
||||
```
|
||||
|
||||
### QueryInterfaceRequest
|
||||
@@ -346,9 +346,8 @@ Functions and methods that build an SQL expression should return an SQLExpressio
|
||||
|
||||
```swift
|
||||
// SELECT * FROM player WHERE LENGTH(name) > 0
|
||||
Player.filter {
|
||||
length($0.name) > 0 // SQLExpression
|
||||
}
|
||||
let expression = length(Column("name")) > 0 // SQLExpression
|
||||
Player.filter(expression)
|
||||
```
|
||||
|
||||
When it looks like GRDB APIs are unable to build a particular expression, use [SQL]:
|
||||
@@ -359,7 +358,7 @@ func date(_ value: SQLSpecificExpressible) -> SQLExpression {
|
||||
}
|
||||
|
||||
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
|
||||
let request = Player.filter { date($0.createdAt) == "2020-01-23" }
|
||||
let request = Player.filter(date(Column("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:
|
||||
@@ -369,7 +368,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($0.createdAt) == "2020-01-23" }
|
||||
.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
.including(required: Player.team)
|
||||
```
|
||||
|
||||
@@ -584,7 +583,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 { $0.score >= averageScore }
|
||||
Player.filter(Column("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($0.createdAt) == "2020-01-23" }
|
||||
let request = Player.filter(date(Column("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(\.score.desc)
|
||||
.order(scoreColumn.desc)
|
||||
.limit(10)
|
||||
.fetchAll(db)
|
||||
|
||||
// SELECT MAX(score) FROM player
|
||||
let maximumScore: Int? = try Player
|
||||
.select { max($0.score) }
|
||||
.select(max(scoreColumn))
|
||||
.asRequestOf(Int.self)
|
||||
.fetchOne(db)
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '7.6.1'
|
||||
s.version = '7.3.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -68,7 +68,6 @@
|
||||
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 */; };
|
||||
@@ -273,7 +272,6 @@
|
||||
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 */; };
|
||||
@@ -489,7 +487,6 @@
|
||||
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>"; };
|
||||
@@ -770,7 +767,6 @@
|
||||
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>"; };
|
||||
@@ -1288,7 +1284,6 @@
|
||||
568D13182207213E00674B58 /* SQLQueryGenerator.swift */,
|
||||
56F89E142A585C0B002FE2AA /* SQLTableAlterationGenerator.swift */,
|
||||
56F89E0B2A57EC16002FE2AA /* SQLTableGenerator.swift */,
|
||||
56231A432DCF3A19007676E4 /* TableAlias.swift */,
|
||||
);
|
||||
path = SQLGeneration;
|
||||
sourceTree = "<group>";
|
||||
@@ -1597,13 +1592,13 @@
|
||||
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 */,
|
||||
@@ -1613,7 +1608,6 @@
|
||||
56AFEF2E29969F6E00CA1E51 /* TransactionClock.swift */,
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
|
||||
56B7EE822863781300C0525F /* WALSnapshot.swift */,
|
||||
56D3331F29C38D6700430680 /* WALSnapshotTransaction.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
);
|
||||
path = Core;
|
||||
@@ -2174,7 +2168,6 @@
|
||||
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 */,
|
||||
@@ -2183,7 +2176,6 @@
|
||||
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 */,
|
||||
|
||||
@@ -144,7 +144,7 @@ public struct Configuration: Sendable {
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter { $0.email == email }.fetchOne(db)
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// // By default, sensitive information is NOT printed
|
||||
/// // when an error occurs:
|
||||
@@ -173,7 +173,7 @@ public struct Configuration: Sendable {
|
||||
/// do {
|
||||
/// // The sensitive information to protect
|
||||
/// let email = "..."
|
||||
/// let player = try Player.filter { $0.email == email }.fetchOne(db)
|
||||
/// let player = try Player.filter(Column("email") == email).fetchOne(db)
|
||||
/// } catch {
|
||||
/// // Sensitive information is printed in DEBUG builds:
|
||||
/// print(error)
|
||||
|
||||
@@ -494,9 +494,11 @@ extension Database {
|
||||
|
||||
switch ResultCode(rawValue: resultCode) {
|
||||
case .SQLITE_INTERRUPT, .SQLITE_ABORT:
|
||||
// The only error that a user sees when a Task is cancelled
|
||||
// is CancellationError.
|
||||
try suspensionMutex.load().checkCancellation()
|
||||
if suspensionMutex.load().isCancelled {
|
||||
// The only error that a user sees when a Task is cancelled
|
||||
// is CancellationError.
|
||||
throw CancellationError()
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
+17
-63
@@ -341,22 +341,10 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
/// If true, the database access has been cancelled.
|
||||
var isCancelled: Bool
|
||||
|
||||
/// If true, the database throws an error when it is cancelled.
|
||||
var interruptsWhenCancelled: Bool
|
||||
|
||||
func checkCancellation() throws {
|
||||
if isCancelled, interruptsWhenCancelled {
|
||||
throw CancellationError()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Support for `checkForSuspensionViolation(from:)`
|
||||
let suspensionMutex = Mutex(Suspension(
|
||||
isSuspended: false,
|
||||
isCancelled: false,
|
||||
interruptsWhenCancelled: true))
|
||||
let suspensionMutex = Mutex(Suspension(isSuspended: false, isCancelled: false))
|
||||
|
||||
// MARK: - Transaction Date
|
||||
|
||||
@@ -1149,9 +1137,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
|
||||
// See <https://www.sqlite.org/c3ref/interrupt.html>
|
||||
func interrupt() {
|
||||
if let sqliteConnection {
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
}
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
}
|
||||
|
||||
// MARK: - Database Suspension
|
||||
@@ -1225,31 +1211,22 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// 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
|
||||
}
|
||||
|
||||
if needsInterrupt {
|
||||
if let sqliteConnection = connection.sqliteConnection {
|
||||
sqlite3_interrupt(sqliteConnection)
|
||||
}
|
||||
}
|
||||
suspension.isCancelled = true
|
||||
return true
|
||||
}
|
||||
|
||||
if needsInterrupt {
|
||||
interrupt()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1260,24 +1237,6 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
/// Within the given closure, Task cancellation does not interrupt
|
||||
/// database accesses.
|
||||
func ignoringCancellation<T>(_ value: () throws -> T) rethrows -> T {
|
||||
let previous = suspensionMutex.withLock {
|
||||
let previous = $0.interruptsWhenCancelled
|
||||
$0.interruptsWhenCancelled = false
|
||||
return previous
|
||||
}
|
||||
|
||||
defer {
|
||||
suspensionMutex.withLock {
|
||||
$0.interruptsWhenCancelled = previous
|
||||
}
|
||||
}
|
||||
|
||||
return try value()
|
||||
}
|
||||
|
||||
/// Support for `checkForSuspensionViolation(from:)`
|
||||
private func journalMode() throws -> String {
|
||||
if let journalMode = journalModeCache {
|
||||
@@ -1329,11 +1288,6 @@ 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 {
|
||||
@@ -1349,7 +1303,7 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
let interrupt: Interrupt? = try suspensionMutex.withLock { suspension in
|
||||
// Check for cancellation first, so that the only error that
|
||||
// a user sees when a Task is cancelled is CancellationError.
|
||||
if suspension.isCancelled, suspension.interruptsWhenCancelled {
|
||||
if suspension.isCancelled {
|
||||
return .cancel
|
||||
}
|
||||
|
||||
|
||||
@@ -173,20 +173,13 @@ 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($0.score) }, as: Int.self)
|
||||
/// .select(square(Column("score")), as: Int.self)
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
@@ -464,7 +457,7 @@ public final class DatabaseFunction: Identifiable, Sendable {
|
||||
/// try Int.fetchOne(db, sql: "SELECT mysum(i) FROM test")! // 3
|
||||
/// }
|
||||
/// ```
|
||||
public protocol DatabaseAggregate: SendableMetatype {
|
||||
public protocol DatabaseAggregate {
|
||||
/// Creates an aggregate.
|
||||
///
|
||||
/// A new instance is created for each aggregation.
|
||||
|
||||
@@ -352,24 +352,40 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
GRDBPrecondition(currentReader == nil, "Database methods are not reentrant.")
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
return try await readerPool.get { reader in
|
||||
try await reader.execute { db in
|
||||
defer {
|
||||
// Ignore commit error, but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
assert(!db.isInsideTransaction)
|
||||
}
|
||||
// The block isolation comes from the DEFERRED transaction.
|
||||
try db.beginTransaction(.deferred)
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -387,9 +403,7 @@ extension DatabasePool: DatabaseReader {
|
||||
// Second async jump because that's how `Pool.async` has to be used.
|
||||
reader.async { db in
|
||||
defer {
|
||||
// Ignore commit error, but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
@@ -422,16 +436,35 @@ extension DatabasePool: DatabaseReader {
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
return try await readerPool.get { reader in
|
||||
try await reader.execute { db in
|
||||
try db.clearSchemaCacheIfNeeded()
|
||||
return try value(db)
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -551,9 +584,7 @@ extension DatabasePool: DatabaseReader {
|
||||
let (reader, releaseReader) = try readerPool.get()
|
||||
reader.async { db in
|
||||
defer {
|
||||
// Ignore commit error, but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.commit() // Ignore commit error
|
||||
releaseReader(.reuse)
|
||||
}
|
||||
do {
|
||||
@@ -771,7 +802,7 @@ extension DatabasePool: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(updates)
|
||||
}
|
||||
@@ -787,32 +818,22 @@ extension DatabasePool: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
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()
|
||||
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)
|
||||
}
|
||||
cancelMutex.store(db.cancel)
|
||||
try Task.checkCancellation()
|
||||
return try updates(db)
|
||||
continuation.resume(returning: result)
|
||||
} catch {
|
||||
continuation.resume(throwing: error)
|
||||
}
|
||||
}
|
||||
} onCancel: {
|
||||
cancelMutex.withLock { $0?() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -234,7 +234,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute { db in
|
||||
try db.isolated(readOnly: true) {
|
||||
@@ -248,9 +248,8 @@ extension DatabaseQueue: DatabaseReader {
|
||||
) {
|
||||
writer.async { db in
|
||||
defer {
|
||||
// Ignore commit error (we can not notify it), but make sure we leave the transaction
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
@@ -273,7 +272,7 @@ extension DatabaseQueue: DatabaseReader {
|
||||
}
|
||||
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(value)
|
||||
}
|
||||
@@ -297,9 +296,8 @@ extension DatabaseQueue: DatabaseReader {
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
|
||||
defer {
|
||||
// Ignore commit error (we can not notify it), but make sure we leave the transaction
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
assert(!db.isInsideTransaction)
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
@@ -387,7 +385,7 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func writeWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writer.execute(updates)
|
||||
}
|
||||
@@ -398,7 +396,7 @@ extension DatabaseQueue: DatabaseWriter {
|
||||
}
|
||||
|
||||
public func barrierWriteWithoutTransaction<T: Sendable>(
|
||||
_ updates: @Sendable (Database) throws -> T
|
||||
_ updates: @escaping @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(_:)-5mfwu``
|
||||
/// - ``read(_:)-4d1da``
|
||||
/// - ``readPublisher(receiveOn:value:)``
|
||||
/// - ``asyncRead(_:)``
|
||||
///
|
||||
/// ### Unsafe Methods
|
||||
///
|
||||
/// - ``unsafeRead(_:)-5i7tf``
|
||||
/// - ``unsafeRead(_:)-90w0p``
|
||||
/// - ``unsafeRead(_:)-5gsav``
|
||||
/// - ``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: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @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: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @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: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @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: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.unsafeRead(value)
|
||||
}
|
||||
|
||||
@@ -201,7 +201,7 @@ extension DatabasePublishers {
|
||||
self.observation = observation
|
||||
}
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber & SendableMetatype, Failure == S.Failure, Output == S.Input {
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = DatabaseRegionSubscription(
|
||||
writer: writer,
|
||||
observation: observation,
|
||||
@@ -212,7 +212,7 @@ extension DatabasePublishers {
|
||||
|
||||
private class DatabaseRegionSubscription<Downstream>:
|
||||
Subscription, @unchecked Sendable
|
||||
where Downstream: Subscriber & SendableMetatype,
|
||||
where Downstream: Subscriber,
|
||||
Downstream.Failure == Error,
|
||||
Downstream.Input == Database
|
||||
{
|
||||
|
||||
@@ -113,9 +113,7 @@ public final class DatabaseSnapshot {
|
||||
deinit {
|
||||
// Leave snapshot isolation
|
||||
reader.reentrantSync { db in
|
||||
// Ignore commit error (we can not notify it), but make sure we leave the transaction
|
||||
try? db.commit()
|
||||
assert(!db.isInsideTransaction)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -154,7 +152,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await reader.execute(value)
|
||||
}
|
||||
@@ -175,7 +173,7 @@ extension DatabaseSnapshot: DatabaseSnapshotReader {
|
||||
// `DatabaseSnapshotReader`, because of
|
||||
// <https://github.com/apple/swift/issues/74469>.
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await read(value)
|
||||
}
|
||||
|
||||
@@ -294,25 +294,36 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
guard let readerPool else {
|
||||
throw DatabaseError.connectionIsClosed()
|
||||
}
|
||||
|
||||
let (reader, releaseReader) = try await readerPool.get()
|
||||
var readerCompletion: PoolCompletion?
|
||||
defer {
|
||||
// readerCompletion might be null in cancelled database accesses
|
||||
releaseReader(readerCompletion ?? .reuse)
|
||||
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 (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(
|
||||
@@ -342,7 +353,7 @@ extension DatabaseSnapshotPool: DatabaseSnapshotReader {
|
||||
// `DatabaseSnapshotReader`, because of
|
||||
// <https://github.com/apple/swift/issues/74469>.
|
||||
public func unsafeRead<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await read(value)
|
||||
}
|
||||
|
||||
@@ -541,20 +541,13 @@ 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(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -591,20 +584,13 @@ 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(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -637,20 +623,13 @@ 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(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -678,20 +657,13 @@ 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(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -724,20 +696,13 @@ 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 { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -771,20 +736,13 @@ 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 { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -814,20 +772,13 @@ 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 { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -857,8 +808,8 @@ extension FetchRequest where RowDecoder: DatabaseValueConvertible & Hashable {
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
|
||||
@@ -22,18 +22,18 @@ import Dispatch
|
||||
/// ### Writing into the Database
|
||||
///
|
||||
/// - ``write(_:)-76inz``
|
||||
/// - ``write(_:)-4gnqx``
|
||||
/// - ``write(_:)-3db50``
|
||||
/// - ``writePublisher(receiveOn:updates:)``
|
||||
/// - ``writePublisher(receiveOn:updates:thenRead:)``
|
||||
/// - ``writeWithoutTransaction(_:)-4qh1w``
|
||||
/// - ``writeWithoutTransaction(_:)-18zhj``
|
||||
/// - ``writeWithoutTransaction(_:)-67mri``
|
||||
/// - ``asyncWrite(_:completion:)``
|
||||
/// - ``asyncWriteWithoutTransaction(_:)``
|
||||
///
|
||||
/// ### Exclusive Access to the Database
|
||||
///
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-280j1``
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-11q6c``
|
||||
/// - ``barrierWriteWithoutTransaction(_:)-48d63``
|
||||
/// - ``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: @Sendable (Database) throws -> T
|
||||
_ updates: @escaping @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: @Sendable (Database) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T
|
||||
|
||||
/// Schedules database operations for execution, and returns immediately.
|
||||
@@ -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: @Sendable (Database) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await writeWithoutTransaction { db in
|
||||
var result: T?
|
||||
@@ -885,7 +885,7 @@ extension AnyDatabaseWriter: DatabaseReader {
|
||||
}
|
||||
|
||||
public func read<T: Sendable>(
|
||||
_ value: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @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: @Sendable (Database) throws -> T
|
||||
_ value: @escaping @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: @Sendable (Database) throws -> T
|
||||
_ updates: @escaping @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: @Sendable (Database) throws -> T
|
||||
_ updates: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
try await base.barrierWriteWithoutTransaction(updates)
|
||||
}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import Dispatch
|
||||
|
||||
/// 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))
|
||||
}
|
||||
}
|
||||
+117
-386
@@ -52,8 +52,6 @@ import Foundation
|
||||
/// - ``subscript(_:)-9c1fw``
|
||||
/// - ``subscript(_:)-3jhwm``
|
||||
/// - ``subscript(_:)-7krrg``
|
||||
/// - ``decode(_:atIndex:)-33ykh``
|
||||
/// - ``decode(_:atIndex:)-3btwn``
|
||||
/// - ``withUnsafeData(atIndex:_:)``
|
||||
/// - ``dataNoCopy(atIndex:)``
|
||||
///
|
||||
@@ -63,8 +61,7 @@ import Foundation
|
||||
/// - ``subscript(_:)-4k8od``
|
||||
/// - ``subscript(_:)-9rbo7``
|
||||
/// - ``coalesce(_:)-359k7``
|
||||
/// - ``decode(_:forColumn:)-4i1o4``
|
||||
/// - ``decode(_:forColumn:)-4rhs4``
|
||||
/// - ``coalesce(_:)-6nbah``
|
||||
/// - ``withUnsafeData(named:_:)``
|
||||
/// - ``dataNoCopy(named:)``
|
||||
///
|
||||
@@ -73,9 +70,6 @@ import Foundation
|
||||
/// - ``subscript(_:)-9txgm``
|
||||
/// - ``subscript(_:)-2esg7``
|
||||
/// - ``subscript(_:)-wl9a``
|
||||
/// - ``coalesce(_:)-6nbah``
|
||||
/// - ``decode(_:forColumn:)-1ljuo``
|
||||
/// - ``decode(_:forColumn:)-47qeg``
|
||||
/// - ``withUnsafeData(at:_:)``
|
||||
/// - ``dataNoCopy(_:)``
|
||||
///
|
||||
@@ -90,10 +84,6 @@ import Foundation
|
||||
/// - ``subscript(_:)-8god3``
|
||||
/// - ``subscript(_:)-jwnx``
|
||||
/// - ``subscript(_:)-6ge6t``
|
||||
/// - ``decode(_:forKey:)-9bbd3``
|
||||
/// - ``decode(_:forKey:)-2w6lc``
|
||||
/// - ``decode(_:forKey:)-2soc2``
|
||||
/// - ``decodeIfPresent(_:forKey:)``
|
||||
/// - ``PrefetchedRowsView``
|
||||
/// - ``ScopesTreeView``
|
||||
/// - ``ScopesView``
|
||||
@@ -129,10 +119,6 @@ import Foundation
|
||||
///
|
||||
/// - ``RowAdapter``
|
||||
///
|
||||
/// ### Errors
|
||||
///
|
||||
/// - ``RowDecodingError``
|
||||
///
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``RowCursor``
|
||||
@@ -466,7 +452,7 @@ extension Row {
|
||||
/// ```
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ columnName: String) -> Value {
|
||||
try! decode(Value.self, forColumn: columnName)
|
||||
try! decode(Value.self, forKey: columnName)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -503,7 +489,7 @@ extension Row {
|
||||
/// ```
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible & StatementColumnConvertible>(_ columnName: String) -> Value {
|
||||
try! decode(Value.self, forColumn: columnName)
|
||||
try! decode(Value.self, forKey: columnName)
|
||||
}
|
||||
|
||||
/// Returns `Int64`, `Double`, `String`, `Data` or nil, depending on the
|
||||
@@ -547,7 +533,7 @@ extension Row {
|
||||
/// ```
|
||||
@inlinable
|
||||
public subscript<Value: DatabaseValueConvertible>(_ column: some ColumnExpression) -> Value {
|
||||
try! decode(Value.self, forColumn: column)
|
||||
try! decode(Value.self, forKey: column.name)
|
||||
}
|
||||
|
||||
/// Returns the value at given column, converted to the requested type.
|
||||
@@ -587,7 +573,7 @@ extension Row {
|
||||
-> Value
|
||||
where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
{
|
||||
try! decode(Value.self, forColumn: column)
|
||||
try! decode(Value.self, forKey: column.name)
|
||||
}
|
||||
|
||||
/// Calls the given closure with the `Data` at given index.
|
||||
@@ -753,13 +739,12 @@ extension Row {
|
||||
|
||||
// MARK: - Extracting Records
|
||||
|
||||
/// Returns the record associated to the given key.
|
||||
/// The record associated to the given scope.
|
||||
///
|
||||
/// 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.
|
||||
/// 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.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
@@ -784,28 +769,26 @@ extension Row {
|
||||
/// let request = Book
|
||||
/// .including(required: Book.author
|
||||
/// .including(required: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// let bookRow = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author = row["author"]
|
||||
/// let country: Country = row["country"]
|
||||
/// let book = try Book(row: bookRow)
|
||||
/// let author: Author = bookRow["author"]
|
||||
/// let country: Country = bookRow["country"]
|
||||
/// ```
|
||||
///
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
/// See also: ``scopesTree``
|
||||
///
|
||||
/// - parameter scope: A scope identifier.
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record {
|
||||
try! decode(Record.self, forKey: scope)
|
||||
}
|
||||
|
||||
/// Returns the eventual record associated to the given key.
|
||||
/// The eventual record associated to the given scope.
|
||||
///
|
||||
/// 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.
|
||||
/// 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.
|
||||
///
|
||||
/// A breadth-first search is performed in all available scopes in the row,
|
||||
/// recursively.
|
||||
@@ -826,26 +809,25 @@ extension Row {
|
||||
///
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// // Fetch a book, with its eventual author, and the country of its author.
|
||||
/// // Fetch a book, with its 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 bookRow = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author? = row["author"]
|
||||
/// let country: Country? = row["country"]
|
||||
/// let book = try Book(row: bookRow)
|
||||
/// let author: Author? = bookRow["author"]
|
||||
/// let country: Country? = bookRow["country"]
|
||||
/// ```
|
||||
///
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
/// See also: ``scopesTree``
|
||||
///
|
||||
/// - parameter scope: A scope identifier.
|
||||
public subscript<Record: FetchableRecord>(_ scope: String) -> Record? {
|
||||
try! decodeIfPresent(Record.self, forKey: scope)
|
||||
}
|
||||
|
||||
/// Returns a collection of prefetched records associated to the given
|
||||
/// A collection of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
@@ -861,10 +843,10 @@ extension Row {
|
||||
/// struct Book: TableRecord, FetchableRecord { }
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// let authorRow = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: [Book] = row["books"]
|
||||
/// let author = try Author(row: authorRow)
|
||||
/// let books: [Book] = author["books"]
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
@@ -879,8 +861,7 @@ extension Row {
|
||||
try! decode(Records.self, forKey: key)
|
||||
}
|
||||
|
||||
/// Returns the set of prefetched records associated to the given
|
||||
/// association key.
|
||||
/// A set prefetched records associated to the given association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
/// request method.
|
||||
@@ -895,10 +876,10 @@ extension Row {
|
||||
/// struct Book: TableRecord, FetchableRecord, Hashable { }
|
||||
///
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
/// let authorRow = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// let author = try Author(row: row)
|
||||
/// let books: Set<Book> = row["books"]
|
||||
/// let author = try Author(row: authorRow)
|
||||
/// let books: Set<Book> = author["books"]
|
||||
/// ```
|
||||
///
|
||||
/// See also: ``prefetchedRows``
|
||||
@@ -954,8 +935,7 @@ extension Row {
|
||||
/// // Prints [code:"US" name:"United States of America"]
|
||||
/// ```
|
||||
///
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
/// See also ``scopesTree``.
|
||||
public var scopes: ScopesView {
|
||||
impl.scopes(prefetchedRows: prefetchedRows)
|
||||
}
|
||||
@@ -1085,28 +1065,10 @@ extension Row {
|
||||
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
|
||||
/// rightmost column.
|
||||
///
|
||||
/// 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.
|
||||
/// If the SQLite value is NULL, or if the conversion fails, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible>(
|
||||
func decode<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value
|
||||
@@ -1120,37 +1082,13 @@ extension Row {
|
||||
/// 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: "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.
|
||||
/// 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.
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible>(
|
||||
func decode<Value: DatabaseValueConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forColumn columnName: String)
|
||||
forKey columnName: String)
|
||||
throws -> Value
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
@@ -1162,47 +1100,6 @@ 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
|
||||
@@ -1217,29 +1114,11 @@ extension Row {
|
||||
/// Indexes span from `0` for the leftmost column to `row.count - 1` for the
|
||||
/// rightmost column.
|
||||
///
|
||||
/// 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.
|
||||
/// If the SQLite value is NULL, or if the conversion fails, a
|
||||
/// `RowDecodingError` is thrown.
|
||||
@inline(__always)
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
atIndex index: Int)
|
||||
throws -> Value
|
||||
@@ -1257,37 +1136,13 @@ extension Row {
|
||||
/// 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: "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.
|
||||
/// 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.
|
||||
@inlinable
|
||||
public func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
func decode<Value: DatabaseValueConvertible & StatementColumnConvertible>(
|
||||
_ type: Value.Type = Value.self,
|
||||
forColumn columnName: String)
|
||||
forKey columnName: String)
|
||||
throws -> Value
|
||||
{
|
||||
guard let index = index(forColumn: columnName) else {
|
||||
@@ -1300,51 +1155,6 @@ 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>(
|
||||
@@ -1377,51 +1187,37 @@ extension Row {
|
||||
// MARK: - Throwing Record Decoding Methods
|
||||
|
||||
extension Row {
|
||||
/// 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.
|
||||
/// Returns the eventual record associated with the given scope.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Book: TableRecord, FetchableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
/// let request = Book.including(optional: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let country = belongsTo(Country.self)
|
||||
/// }
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
/// let author: Author? = row["author"]
|
||||
/// print(author.name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// // 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)!
|
||||
/// Associated records stored in nested associations are available, too:
|
||||
///
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author? = try row.decode(forKey: "author")
|
||||
/// let country: Country? = try row.decode(forKey: "country")
|
||||
/// ```
|
||||
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// - parameter type: The decoded type.
|
||||
/// - parameter scope: A scope identifier.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decodeIfPresent<Record: FetchableRecord>(
|
||||
/// 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>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
throws -> Record?
|
||||
@@ -1432,48 +1228,37 @@ extension Row {
|
||||
return try Record(row: scopedRow)
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// Returns the record associated with the given scope.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Book: TableRecord, FetchableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
/// let request = Book.including(required: Book.author)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let country = belongsTo(Country.self)
|
||||
/// }
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// struct Country: TableRecord, FetchableRecord { }
|
||||
/// let author: Author = row["author"]
|
||||
/// print(author.name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// // 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)!
|
||||
/// Associated records stored in nested associations are available, too:
|
||||
///
|
||||
/// let book = try Book(row: row)
|
||||
/// let author: Author = try row.decode(forKey: "author")
|
||||
/// let country: Country = try row.decode(forKey: "country")
|
||||
/// ```
|
||||
/// let request = Book.including(required: Book.author.including(required: Author.country))
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// For more details about row scopes, see ``ScopeAdapter``,
|
||||
/// ``splittingRowAdapters(columnCounts:)`` and ``scopesTree``.
|
||||
/// try print(Book(row: row).title)
|
||||
/// // Prints "Moby-Dick"
|
||||
///
|
||||
/// - parameter type: The decoded type.
|
||||
/// - parameter scope: A scope identifier.
|
||||
/// - throws: Any error that happens during the decoding.
|
||||
public func decode<Record: FetchableRecord>(
|
||||
/// 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>(
|
||||
_ type: Record.Type = Record.self,
|
||||
forKey scope: String)
|
||||
throws -> Record
|
||||
@@ -1515,34 +1300,20 @@ extension Row {
|
||||
// MARK: - Throwing Record RangeReplaceableCollection and Set Methods
|
||||
|
||||
extension Row {
|
||||
/// Returns a collection of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
/// request method.
|
||||
/// Returns the records encoded in the given prefetched rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let books = hasMany(Book.self)
|
||||
/// }
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// struct Book: TableRecord, FetchableRecord { }
|
||||
/// try print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// 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>(
|
||||
/// let books: [Book] = row["books"]
|
||||
/// print(books[0].title)
|
||||
/// // Prints "Moby-Dick"
|
||||
func decode<Collection>(
|
||||
_ type: Collection.Type = Collection.self,
|
||||
forKey key: String)
|
||||
throws -> Collection
|
||||
@@ -1550,7 +1321,6 @@ extension Row {
|
||||
Collection: RangeReplaceableCollection,
|
||||
Collection.Element: FetchableRecord
|
||||
{
|
||||
// TODO: test independently
|
||||
guard let rows = prefetchedRows[key] else {
|
||||
let availableKeys = prefetchedRows.keys
|
||||
if availableKeys.isEmpty {
|
||||
@@ -1581,39 +1351,24 @@ extension Row {
|
||||
return collection
|
||||
}
|
||||
|
||||
/// Returns the set of prefetched records associated to the given
|
||||
/// association key.
|
||||
///
|
||||
/// Prefetched rows are defined by the ``JoinableRequest/including(all:)``
|
||||
/// request method.
|
||||
/// Returns the set of records encoded in the given prefetched rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord, FetchableRecord {
|
||||
/// static let books = hasMany(Book.self)
|
||||
/// }
|
||||
/// let request = Author.including(all: Author.books)
|
||||
/// let row = try Row.fetchOne(db, request)!
|
||||
///
|
||||
/// struct Book: TableRecord, FetchableRecord, Hashable { }
|
||||
/// try print(Author(row: row).name)
|
||||
/// // Prints "Herman Melville"
|
||||
///
|
||||
/// 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>(
|
||||
/// let books: Set<Book> = row["books"]
|
||||
/// print(books.first!.title)
|
||||
/// // Prints "Moby-Dick"
|
||||
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 {
|
||||
@@ -1980,17 +1735,11 @@ 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 { $0.lastName == lastName }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -2035,17 +1784,11 @@ 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 { $0.lastName == lastName }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -2073,17 +1816,11 @@ 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 { $0.lastName == lastName }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
@@ -2115,17 +1852,11 @@ 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 { $0.lastName == lastName }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Row> = """
|
||||
|
||||
@@ -23,21 +23,9 @@ enum RowKey: Hashable, Sendable {
|
||||
case prefetchKey(String)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// A decoding error
|
||||
@usableFromInline
|
||||
enum RowDecodingError: Error {
|
||||
@usableFromInline
|
||||
struct Context: CustomDebugStringConvertible, Sendable {
|
||||
/// A description of what went wrong, for debugging purposes.
|
||||
@@ -67,19 +55,17 @@ public struct RowDecodingError: Error {
|
||||
}
|
||||
}
|
||||
|
||||
var impl: Impl
|
||||
case keyNotFound(RowKey, Context)
|
||||
case valueMismatch(Any.Type, Context)
|
||||
|
||||
var context: Context {
|
||||
switch impl {
|
||||
switch self {
|
||||
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(
|
||||
@@ -88,10 +74,11 @@ public struct RowDecodingError: Error {
|
||||
databaseValue: DatabaseValue)
|
||||
-> Self
|
||||
{
|
||||
let context = RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
could not decode \(type) from database value \(databaseValue)
|
||||
""")
|
||||
return self.init(impl: .valueMismatch(type, context))
|
||||
valueMismatch(
|
||||
type,
|
||||
RowDecodingError.Context(decodingContext: context, debugDescription: """
|
||||
could not decode \(type) from database value \(databaseValue)
|
||||
"""))
|
||||
}
|
||||
|
||||
/// Convenience method that builds the
|
||||
@@ -128,15 +115,11 @@ public struct RowDecodingError: Error {
|
||||
/// error message.
|
||||
@usableFromInline
|
||||
static func columnNotFound(_ columnName: String, context: RowDecodingContext) -> Self {
|
||||
self.init(impl: .keyNotFound(
|
||||
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))
|
||||
"""))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,7 +167,8 @@ struct RowDecodingContext {
|
||||
}
|
||||
|
||||
extension RowDecodingError: CustomStringConvertible {
|
||||
public var description: String {
|
||||
@usableFromInline
|
||||
var description: String {
|
||||
let context = self.context
|
||||
let row = context.row
|
||||
var chunks: [String] = []
|
||||
|
||||
+7
-2
@@ -118,7 +118,7 @@ public struct SQL: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
fileprivate func qualified(with alias: TableAliasBase) -> Element {
|
||||
fileprivate func qualified(with alias: TableAlias) -> Element {
|
||||
switch self {
|
||||
case .sql:
|
||||
// A raw SQL string can't be qualified with a table alias,
|
||||
@@ -172,6 +172,11 @@ public struct SQL: Sendable {
|
||||
self.init(elements: [.expression(expression.sqlExpression)])
|
||||
}
|
||||
|
||||
/// Creates an `SQL` literal from an SQL ordering term.
|
||||
public init(_ ordering: some SQLOrderingTerm) {
|
||||
self.init(elements: [.ordering(ordering.sqlOrdering)])
|
||||
}
|
||||
|
||||
/// Returns true if this literal generates an empty SQL string
|
||||
public var isEmpty: Bool {
|
||||
elements.allSatisfy(\.isEmpty)
|
||||
@@ -192,7 +197,7 @@ public struct SQL: Sendable {
|
||||
try elements.map { try $0.sql(context) }.joined()
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAliasBase) -> SQL {
|
||||
func qualified(with alias: TableAlias) -> SQL {
|
||||
SQL(elements: elements.map { $0.qualified(with: alias) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,9 +5,6 @@ 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 }
|
||||
|
||||
@@ -58,8 +55,6 @@ final class SerializedDatabase {
|
||||
} else {
|
||||
self.queue = configuration.makeWriterDispatchQueue(label: identifier)
|
||||
}
|
||||
self.actor = DispatchQueueActor(queue: queue)
|
||||
|
||||
SchedulingWatchdog.allowDatabase(db, onQueue: queue)
|
||||
try queue.sync {
|
||||
do {
|
||||
@@ -250,22 +245,20 @@ final class SerializedDatabase {
|
||||
|
||||
/// Asynchrously executes the block.
|
||||
func execute<T: Sendable>(
|
||||
_ block: @Sendable (Database) throws -> T
|
||||
_ block: @escaping @Sendable (Database) throws -> T
|
||||
) async throws -> T {
|
||||
let cancelMutex = Mutex<(@Sendable () -> Void)?>(nil)
|
||||
return try await withTaskCancellationHandler {
|
||||
try await actor.execute {
|
||||
defer {
|
||||
cancelMutex.store(nil)
|
||||
db.uncancel()
|
||||
preconditionNoUnsafeTransactionLeft(db)
|
||||
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)
|
||||
}
|
||||
cancelMutex.store(db.cancel)
|
||||
try Task.checkCancellation()
|
||||
return try block(db)
|
||||
}
|
||||
} onCancel: {
|
||||
cancelMutex.withLock { $0?() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,3 +305,108 @@ 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()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -563,20 +563,13 @@ 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(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -615,20 +608,13 @@ 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(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -661,20 +647,13 @@ 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(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -702,20 +681,13 @@ 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(\.score)
|
||||
/// .filter { $0.lastName == lastName }
|
||||
/// .select(Column("score"))
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -748,20 +720,13 @@ 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 { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -795,20 +760,13 @@ 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 { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -838,20 +796,13 @@ 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 { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
@@ -876,20 +827,13 @@ 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 { $0.lastName == lastName }
|
||||
/// .select(\.score, as: Int.self)
|
||||
/// .filter(Column("lastName") == lastName)
|
||||
/// .select(Column("score"), as: Int.self)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Int> = """
|
||||
|
||||
@@ -650,7 +650,8 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/capitalized``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let request = Player.select { $0.name.capitalized }
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.capitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let capitalize =
|
||||
@@ -671,7 +672,8 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/lowercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let request = Player.select { $0.name.lowercased }
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.lowercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let lowercase =
|
||||
@@ -692,7 +694,8 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/uppercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let request = Player.select { $0.name.uppercased }
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.uppercased)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let uppercase =
|
||||
@@ -713,7 +716,8 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/localizedCapitalized``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let request = Player.select { $0.name.localizedCapitalized }
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedCapitalized)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let localizedCapitalize =
|
||||
@@ -735,7 +739,8 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/localizedLowercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let request = Player.select { $0.name.localizedLowercase }
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedLowercase)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let localizedLowercase =
|
||||
@@ -756,7 +761,8 @@ extension DatabaseFunction {
|
||||
/// ``SQLSpecificExpressible/localizedUppercased``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let request = Player.select { $0.name.localizedUppercase }
|
||||
/// let nameColumn = Column("name")
|
||||
/// let request = Player.select(nameColumn.localizedUppercase)
|
||||
/// let names = try String.fetchAll(dbQueue, request) // [String]
|
||||
/// ```
|
||||
public static let localizedUppercase =
|
||||
|
||||
@@ -549,12 +549,8 @@ class DatabaseObservationBroker {
|
||||
savepointStack.clear()
|
||||
|
||||
if !database.isReadOnly {
|
||||
// Observers must be able to access the database, even if the
|
||||
// task that has performed the commit is cancelled.
|
||||
database.ignoringCancellation {
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidCommit(database)
|
||||
}
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidCommit(database)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -617,13 +613,8 @@ class DatabaseObservationBroker {
|
||||
|
||||
if notifyTransactionObservers {
|
||||
assert(!database.isReadOnly, "Read-only transactions are not notified")
|
||||
|
||||
// Observers must be able to access the database, even if the
|
||||
// task that has performed the commit is cancelled.
|
||||
database.ignoringCancellation {
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidRollback(database)
|
||||
}
|
||||
for observation in transactionObservations {
|
||||
observation.databaseDidRollback(database)
|
||||
}
|
||||
}
|
||||
databaseDidEndTransaction()
|
||||
@@ -1252,16 +1243,16 @@ private struct CopiedDatabaseEventImpl: DatabaseEventImpl {
|
||||
|
||||
public struct DatabasePreUpdateEvent {
|
||||
|
||||
/// An event kind.
|
||||
public enum Kind: CInt, Sendable {
|
||||
/// An insertion event
|
||||
case insert = 18 // SQLITE_INSERT
|
||||
/// An event kind
|
||||
public enum Kind: CInt {
|
||||
/// SQLITE_INSERT
|
||||
case insert = 18
|
||||
|
||||
/// A deletion event
|
||||
case delete = 9 // SQLITE_DELETE
|
||||
/// SQLITE_DELETE
|
||||
case delete = 9
|
||||
|
||||
/// An update event
|
||||
case update = 23 // SQLITE_UPDATE
|
||||
/// SQLITE_UPDATE
|
||||
case update = 23
|
||||
}
|
||||
|
||||
/// The event kind
|
||||
|
||||
@@ -97,7 +97,7 @@ try dbQueue.write { db in
|
||||
}
|
||||
```
|
||||
|
||||
See ``DatabaseReader/read(_:)-5mfwu`` and ``DatabaseWriter/write(_:)-4gnqx``.
|
||||
See ``DatabaseReader/read(_:)-4d1da`` and ``DatabaseWriter/write(_:)-3db50``.
|
||||
|
||||
Note the identical method names: `read`, `write`. The async version is only available in async Swift functions.
|
||||
|
||||
|
||||
@@ -262,11 +262,11 @@ try dbQueue.write { db in
|
||||
|
||||
// Use instead:
|
||||
let player = try Player
|
||||
.filter { $0.teamId == 42 && $0.position == 1 }
|
||||
.filter(Column("teamId") == 42 && Column("position") == 1)
|
||||
.fetchOne(db)
|
||||
|
||||
try Player
|
||||
.filter { $0.name == "Arthur" }
|
||||
.filter(Column("name") == "Arthur")
|
||||
.deleteAll(db)
|
||||
}
|
||||
```
|
||||
|
||||
@@ -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(\.score))
|
||||
tracking: Player.select(Column("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(\.score).filter(id: 1),
|
||||
region: Player.select(Column("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,10 +263,6 @@ 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`.
|
||||
|
||||
@@ -36,16 +36,10 @@ 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 { $0.address["country"] == "DE" }
|
||||
> .filter(JSONColumn("address")["country"] == "DE")
|
||||
> .fetchAll(db)
|
||||
> ```
|
||||
|
||||
@@ -110,16 +104,10 @@ 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 { $0.address == Address(...) }
|
||||
> .filter(JSONColumn("address") == Address(...))
|
||||
> .fetchAll(db)
|
||||
> ```
|
||||
>
|
||||
|
||||
@@ -94,26 +94,6 @@ migrator.registerMigration("Create authors") { db in
|
||||
}
|
||||
```
|
||||
|
||||
#### How to Rename a Foreign Key
|
||||
|
||||
When a migration **renames a foreign key**, make sure the migration runs with `.immediate` foreign key checks, in order to avoid database integrity problems:
|
||||
|
||||
```swift
|
||||
// IMPORTANT: rename foreign keys with immediate foreign key checks.
|
||||
migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in
|
||||
try db.rename(table: "team", to: "guild")
|
||||
|
||||
try db.alter(table: "player") { t in
|
||||
// Rename a foreign key
|
||||
t.rename(column: "teamId", to: "guildId")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Note: migrations that run with `.immediate` foreign key checks can not be used to recreated database tables, as described below. When needed, define two migrations instead of one.
|
||||
|
||||
#### How to Recreate a Database Table
|
||||
|
||||
When you need to modify a table in a way that is not directly supported by SQLite, or not available on your target operating system, you will need to recreate the database table.
|
||||
|
||||
For example:
|
||||
@@ -133,39 +113,19 @@ migrator.registerMigration("Add NOT NULL check on author.name") { db in
|
||||
|
||||
The detailed sequence of operations for recreating a database table from a migration is:
|
||||
|
||||
1. When relevant, remember the format of all indexes, triggers, and views associated with table `X`. This information will be needed in steps 6 below. One way to do this is to run the following statement and examine the output in the console:
|
||||
1. When relevant, remember the format of all indexes, triggers, and views associated with table X. This information will be needed in steps 6 and 7 below. One way to do this is to run a query like the following: `SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'`.
|
||||
|
||||
```swift
|
||||
try db.dumpSQL("SELECT type, sql FROM sqlite_schema WHERE tbl_name='X'")
|
||||
```
|
||||
2. Use `CREATE TABLE` to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course.
|
||||
|
||||
2. Construct a new table `new_X` that is in the desired revised format of table `X`. Make sure that the name `new_X` does not collide with any existing table name, of course.
|
||||
3. Transfer content from X into new_X using a statement like: `INSERT INTO new_X SELECT ... FROM X`.
|
||||
|
||||
```swift
|
||||
try db.create(table: "new_X") { t in ... }
|
||||
```
|
||||
4. Drop the old table X: `DROP TABLE X`.
|
||||
|
||||
3. Transfer content from `X` into `new_X` using a statement like:
|
||||
5. Change the name of new_X to X using: `ALTER TABLE new_X RENAME TO X`.
|
||||
|
||||
```swift
|
||||
try db.execute(sql: "INSERT INTO new_X SELECT ... FROM X")
|
||||
```
|
||||
6. When relevant, use `CREATE INDEX`, `CREATE TRIGGER`, and `CREATE VIEW` to reconstruct indexes, triggers, and views associated with table X. Perhaps use the old format of the triggers, indexes, and views saved from step 3 above as a guide, making changes as appropriate for the alteration.
|
||||
|
||||
4. Drop the old table `X`:
|
||||
|
||||
```swift
|
||||
try db.drop(table: "X")
|
||||
```
|
||||
|
||||
5. Change the name of `new_X` to `X` using:
|
||||
|
||||
```swift
|
||||
try db.rename(table: "new_X", to: "X")
|
||||
```
|
||||
|
||||
6. When relevant, reconstruct indexes, triggers, and views associated with table `X`.
|
||||
|
||||
7. If any views refer to table `X` in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
|
||||
7. If any views refer to table X in a way that is affected by the schema change, then drop those views using `DROP VIEW` and recreate them with whatever changes are necessary to accommodate the schema change using `CREATE VIEW`.
|
||||
|
||||
> Important: When recreating a table, be sure to follow the above procedure exactly, in the given order, or you might corrupt triggers, views, and foreign key constraints.
|
||||
>
|
||||
|
||||
@@ -214,7 +214,7 @@ extension Book.Kind: DatabaseValueConvertible { }
|
||||
|
||||
// Fetch all novels
|
||||
let novels = try dbQueue.read { db in
|
||||
try Book.filter { $0.kind == Book.Kind.novel }.fetchAll(db)
|
||||
try Book.filter(Column("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, with the name `Columns`, nested inside the record type. 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. 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,15 +310,13 @@ extension Author {
|
||||
}
|
||||
```
|
||||
|
||||
For non-Codable record types, declare columns with their names:
|
||||
For other record types, declare a plain `String` enum that conforms to the ``ColumnExpression`` protocol:
|
||||
|
||||
```swift
|
||||
// HOW TO define columns for a non-Codable record
|
||||
extension Author {
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
static let countryCode = Column("countryCode")
|
||||
enum Columns: String, ColumnExpression {
|
||||
case id, name, countryCode
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -330,12 +328,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 { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
|
||||
.fetchAll(db)
|
||||
|
||||
// Count French authors
|
||||
let frenchAuthorCount: Int = try Author.all()
|
||||
.filter { $0.countryCode == "FR" }
|
||||
.filter(Author.Columns.countryCode == "FR")
|
||||
.fetchCount(db)
|
||||
}
|
||||
```
|
||||
@@ -351,12 +349,13 @@ 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 {
|
||||
order { $0.name.collating(.localizedCaseInsensitiveCompare) }
|
||||
let name = Author.Columns.name
|
||||
return order(name.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// Filters authors from a country
|
||||
func filter(countryCode: String) -> Self {
|
||||
filter { $0.countryCode == countryCode }
|
||||
filter(Author.Columns.countryCode == countryCode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -364,12 +363,13 @@ extension DerivableRequest<Author> {
|
||||
extension DerivableRequest<Book> {
|
||||
/// Order books by title, in a localized case-insensitive fashion
|
||||
func orderByTitle() -> Self {
|
||||
order { $0.title.collating(.localizedCaseInsensitiveCompare) }
|
||||
let title = Book.Columns.title
|
||||
return order(title.collating(.localizedCaseInsensitiveCompare))
|
||||
}
|
||||
|
||||
/// Filters books by kind
|
||||
func filter(kind: Book.Kind) -> Self {
|
||||
filter { $0.kind == kind }
|
||||
filter(Book.Columns.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(\.name)
|
||||
select(Author.Columns.name)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -91,14 +91,8 @@ extension Player: FetchableRecord, PersistableRecord {
|
||||
// because non-'Sendable' type '[any SQLSelectable]'
|
||||
// may have shared mutable state
|
||||
static let databaseSelection: [any SQLSelectable] = [
|
||||
Columns.id, Columns.name, Columns.score
|
||||
Column("id"), Column("name"), Column("score")
|
||||
]
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
static let score = Column("score")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -107,7 +101,7 @@ extension Player: FetchableRecord, PersistableRecord {
|
||||
```swift
|
||||
extension Player: FetchableRecord, PersistableRecord {
|
||||
static var databaseSelection: [any SQLSelectable] {
|
||||
[Columns.id, Columns.name, Columns.score]
|
||||
[Column("id"), Column("name"), Column("score")]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
///
|
||||
/// ### Creating Raw FTS5 Patterns
|
||||
///
|
||||
/// - ``init(rawPattern:allowedColumns:)``
|
||||
/// - ``Database/makeFTS5Pattern(rawPattern:forTable:)``
|
||||
///
|
||||
///
|
||||
/// ### Creating FTS5 Patterns from User Input
|
||||
///
|
||||
/// - ``init(matchingAllPrefixesIn:)``
|
||||
@@ -124,25 +123,7 @@ public struct FTS5Pattern: Sendable {
|
||||
try? self.init(rawPattern: "^\"" + tokens.joined(separator: " ") + "\"")
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
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
|
||||
|
||||
@@ -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({ $0.address["countryCode"] }, as: String.self)
|
||||
/// .select(Player.Columns.address["countryCode"], as: String.self)
|
||||
/// .distinct()
|
||||
/// .fetchAll(db)
|
||||
/// }
|
||||
@@ -59,10 +59,8 @@
|
||||
/// > extension Player: FetchableRecord, PersistableRecord {
|
||||
/// > // That's another valid way to define columns.
|
||||
/// > // But we don't have any JSONColumn this time.
|
||||
/// > enum Columns {
|
||||
/// > static let id = Column("id")
|
||||
/// > static let name = Column("name")
|
||||
/// > static let address = Column("address")
|
||||
/// > enum Columns: String, ColumnExpression {
|
||||
/// > case id, name, address
|
||||
/// > }
|
||||
/// > }
|
||||
/// >
|
||||
@@ -70,7 +68,7 @@
|
||||
/// > // Fetch all country codes
|
||||
/// > // SELECT DISTINCT address ->> 'countryCode' FROM player
|
||||
/// > let countryCodes: [String] = try Player
|
||||
/// > .select({ $0.address.asJSON["countryCode"] }, as: String.self)
|
||||
/// > .select(Player.Columns.address.asJSON["countryCode"], as: String.self)
|
||||
/// > .distinct()
|
||||
/// > .fetchAll(db)
|
||||
/// > }
|
||||
|
||||
@@ -135,16 +135,12 @@ extension SQLSpecificExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = Column("info")
|
||||
/// }
|
||||
/// }
|
||||
/// let info = Column("info").asJSON
|
||||
///
|
||||
/// // SELECT info ->> 'firstName' FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select({ $0.info.asJSON["firstName"] }, as: String.self)
|
||||
/// .select(info["firstName"], as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -161,22 +157,18 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT info ->> 'firstName' FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select({ $0.info["firstName"] }, as: String.self)
|
||||
/// .select(info["firstName"], as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT info ->> 'address' FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let address = try Player
|
||||
/// .select({ $0.info["address"] }, as: String.self)
|
||||
/// .select(info["address"], as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -193,22 +185,18 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select({ $0.info.jsonExtract(atPath: "$.firstName") }, as: String.self)
|
||||
/// .select(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({ $0.info.jsonExtract(atPath: "$.address") }, as: String.self)
|
||||
/// .select(info.jsonExtract(atPath: "$.address"), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -224,16 +212,12 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player
|
||||
/// // → '["Arthur","Miller"]'
|
||||
/// let nameComponents = try Player
|
||||
/// .select({ $0.info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]) }, as: String.self)
|
||||
/// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -251,22 +235,18 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT info -> 'firstName' FROM player
|
||||
/// // → '"Arthur"'
|
||||
/// let name = try Player
|
||||
/// .select({ $0.info.jsonRepresentation(atPath: "firstName") }, as: String.self)
|
||||
/// .select(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({ $0.info.jsonRepresentation(atPath: "address") }, as: String.self)
|
||||
/// .select(info.jsonRepresentation(atPath: "address"), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -285,22 +265,18 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT info ->> 'firstName' FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select({ $0.info["firstName"] }, as: String.self)
|
||||
/// .select(info["firstName"], as: String.self)
|
||||
/// .fetchOne(db)
|
||||
///
|
||||
/// // SELECT info ->> 'address' FROM player
|
||||
/// // → '{"street":"Rue de Belleville","city":"Paris"}'
|
||||
/// let address = try Player
|
||||
/// .select({ $0.info["address"] }, as: String.self)
|
||||
/// .select(info["address"], as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -318,22 +294,18 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.firstName') FROM player
|
||||
/// // → 'Arthur'
|
||||
/// let firstName = try Player
|
||||
/// .select({ $0.info.jsonExtract(atPath: "$.firstName") }, as: String.self)
|
||||
/// .select(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({ $0.info.jsonExtract(atPath: "$.address") }, as: String.self)
|
||||
/// .select(info.jsonExtract(atPath: "$.address"), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -350,16 +322,12 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT JSON_EXTRACT(info, '$.firstName', '$.lastName') FROM player
|
||||
/// // → '["Arthur","Miller"]'
|
||||
/// let nameComponents = try Player
|
||||
/// .select({ $0.info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]) }, as: String.self)
|
||||
/// .select(info.jsonExtract(atPaths: ["$.firstName", "$.lastName"]), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
@@ -378,22 +346,18 @@ extension SQLJSONExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let info = JSONColumn("info")
|
||||
/// }
|
||||
/// }
|
||||
/// let info = JSONColumn("info")
|
||||
///
|
||||
/// // SELECT info -> 'firstName' FROM player
|
||||
/// // → '"Arthur"'
|
||||
/// let name = try Player
|
||||
/// .select({ $0.info.jsonRepresentation(atPath: "firstName") }, as: String.self)
|
||||
/// .select(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({ $0.info.jsonRepresentation(atPath: "address") }, as: String.self)
|
||||
/// .select(info.jsonRepresentation(atPath: "address"), as: String.self)
|
||||
/// .fetchOne(db)
|
||||
/// ```
|
||||
///
|
||||
|
||||
@@ -378,21 +378,14 @@ 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($0.name) }
|
||||
/// Player.select(Database.jsonGroupArray(Column("name")))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select { Database.jsonGroupArray($0.name, filter: $0.score > 0) }
|
||||
/// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name ORDER BY name) FROM player
|
||||
/// Player.select { Database.jsonGroupArray($0.name, orderBy: $0.name) }
|
||||
/// Player.select(Database.jsonGroupArray(Column("name"), orderBy: Column("name")))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@@ -414,27 +407,16 @@ 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: $0.name,
|
||||
/// value: $0.score)
|
||||
/// }
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score")))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select {
|
||||
/// Database.jsonGroupObject(
|
||||
/// key: $0.name,
|
||||
/// value: $0.score,
|
||||
/// filter: $0.score > 0)
|
||||
/// }
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score"),
|
||||
/// filter: Column("score") > 0))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@@ -716,21 +698,14 @@ 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($0.name) }
|
||||
/// Player.select(Database.jsonbGroupArray(Column("name")))
|
||||
///
|
||||
/// // SELECT JSONB_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select { Database.jsonbGroupArray($0.name, filter: $0.score > 0) }
|
||||
/// Player.select(Database.jsonbGroupArray(Column("name"), filter: Column("score") > 0))
|
||||
///
|
||||
/// // SELECT JSONB_GROUP_ARRAY(name ORDER BY name) FROM player
|
||||
/// Player.select { Database.jsonbGroupArray($0.name, orderBy: $0.name) }
|
||||
/// Player.select(Database.jsonbGroupArray(Column("name"), orderBy: Column("name")))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@@ -752,27 +727,16 @@ 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: $0.name,
|
||||
/// value: $0.score)
|
||||
/// }
|
||||
/// Player.select(Database.jsonbGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score")))
|
||||
///
|
||||
/// // SELECT JSONB_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select {
|
||||
/// Database.jsonbGroupObject(
|
||||
/// key: $0.name,
|
||||
/// value: $0.score,
|
||||
/// filter: $0.score > 0)
|
||||
/// }
|
||||
/// Player.select(Database.jsonbGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score"),
|
||||
/// filter: Column("score") > 0))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@@ -1161,18 +1125,11 @@ 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($0.name) }
|
||||
/// Player.select(Database.jsonGroupArray(Column("name")))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_ARRAY(name) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select { Database.jsonGroupArray($0.name, filter: $0.score > 0) }
|
||||
/// Player.select(Database.jsonGroupArray(Column("name"), filter: Column("score") > 0))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
@@ -1193,27 +1150,16 @@ 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: $0.name,
|
||||
/// value: $0.score)
|
||||
/// }
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score")))
|
||||
///
|
||||
/// // SELECT JSON_GROUP_OBJECT(name, score) FILTER (WHERE score > 0) FROM player
|
||||
/// Player.select {
|
||||
/// Database.jsonGroupObject(
|
||||
/// key: $0.name,
|
||||
/// value: $0.score,
|
||||
/// filter: $0.score > 0)
|
||||
/// }
|
||||
/// Player.select(Database.jsonGroupObject(
|
||||
/// key: Column("name"),
|
||||
/// value: Column("score"),
|
||||
/// filter: Column("score") > 0))
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/json1.html#jgrouparray>
|
||||
|
||||
@@ -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,14 +25,9 @@
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Book: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let authorId = Column("authorId")
|
||||
/// static let translatorId = Column("translatorId")
|
||||
/// }
|
||||
///
|
||||
/// // Define foreign keys
|
||||
/// static let authorForeignKey = ForeignKey([Columns.authorId]))
|
||||
/// static let translatorForeignKey = ForeignKey([Columns.translatorId]))
|
||||
/// static let authorForeignKey = ForeignKey(["authorId"]))
|
||||
/// static let translatorForeignKey = ForeignKey(["translatorId"]))
|
||||
///
|
||||
/// // Use foreign keys to define associations:
|
||||
/// static let author = belongsTo(
|
||||
@@ -46,6 +41,19 @@
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// 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: TableAliasBase) -> Self {
|
||||
public func aliased(_ alias: TableAlias) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation = relation.aliased(alias)
|
||||
}
|
||||
@@ -281,6 +281,12 @@ extension Association {
|
||||
relation.ctes[cte.tableName] = cte.cte
|
||||
}
|
||||
}
|
||||
|
||||
public func limit(_ limit: Int, offset: Int? = nil) -> Self {
|
||||
withDestinationRelation { relation in
|
||||
relation.limit = SQLLimit(limit: limit, offset: offset)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - AssociationToOne
|
||||
@@ -305,25 +311,15 @@ extension AssociationToOne {
|
||||
///
|
||||
/// ### Building Association Aggregates
|
||||
///
|
||||
/// - ``average(_:)-1ehdb``
|
||||
/// - ``average(_:)``
|
||||
/// - ``count``
|
||||
/// - ``isEmpty``
|
||||
/// - ``max(_:)-a32j``
|
||||
/// - ``min(_:)-41jp8``
|
||||
/// - ``sum(_:)-47yg7``
|
||||
/// - ``total(_:)-6dd9d``
|
||||
/// - ``max(_:)``
|
||||
/// - ``min(_:)``
|
||||
/// - ``sum(_:)``
|
||||
/// - ``total(_:)``
|
||||
///
|
||||
/// - ``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,56 +136,6 @@ 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:
|
||||
@@ -233,56 +183,6 @@ 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:
|
||||
@@ -330,61 +230,10 @@ 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 ``AssociationToMany/total(_:)-56v8i`` and
|
||||
/// <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
/// This aggregate invokes the `SUM` SQL function. See also ``total(_:)``
|
||||
/// and <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -433,63 +282,8 @@ extension AssociationToMany {
|
||||
|
||||
/// Returns the sum of the given expression in associated records.
|
||||
///
|
||||
/// 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>.
|
||||
/// This aggregate invokes the `TOTAL` SQL function. See also ``sum(_:)``
|
||||
/// and <https://www.sqlite.org/lang_aggfunc.html#sumunc>.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -537,64 +331,6 @@ 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.
|
||||
|
||||
@@ -385,18 +385,12 @@ extension CommonTableExpression {
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to cte: CommonTableExpression<Destination>,
|
||||
on condition: @escaping @Sendable (
|
||||
_ left: TableAlias<RowDecoder>,
|
||||
_ right: TableAlias<Destination>
|
||||
) -> any SQLExpressible
|
||||
)
|
||||
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
{
|
||||
JoinAssociation(
|
||||
to: cte.relationForAll,
|
||||
condition: .expression { left, right in
|
||||
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
|
||||
})
|
||||
condition: .expression { condition($0, $1).sqlExpression })
|
||||
}
|
||||
|
||||
/// Creates an association to a common table expression that you can join
|
||||
@@ -427,18 +421,13 @@ extension CommonTableExpression {
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to destination: Destination.Type,
|
||||
on condition: @escaping @Sendable (
|
||||
_ left: TableAlias<RowDecoder>,
|
||||
_ right: TableAlias<Destination>
|
||||
) -> any SQLExpressible)
|
||||
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
where Destination: TableRecord
|
||||
{
|
||||
JoinAssociation(
|
||||
to: Destination.relationForAll,
|
||||
condition: .expression { left, right in
|
||||
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
|
||||
})
|
||||
condition: .expression { condition($0, $1).sqlExpression })
|
||||
}
|
||||
|
||||
/// Creates an association to a table record that you can join
|
||||
@@ -469,17 +458,12 @@ extension CommonTableExpression {
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to destination: Table<Destination>,
|
||||
on condition: @escaping @Sendable (
|
||||
_ left: TableAlias<RowDecoder>,
|
||||
_ right: TableAlias<Destination>
|
||||
) -> any SQLExpressible)
|
||||
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
{
|
||||
JoinAssociation(
|
||||
to: destination.relationForAll,
|
||||
condition: .expression { left, right in
|
||||
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
|
||||
})
|
||||
condition: .expression { condition($0, $1).sqlExpression })
|
||||
}
|
||||
|
||||
/// Creates an association to a table that you can join
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -22,23 +22,14 @@ public protocol TypedRequest<RowDecoder> {
|
||||
///
|
||||
/// ### The SELECT Clause
|
||||
///
|
||||
/// - ``annotated(with:)-9wodv``
|
||||
/// - ``annotated(with:)-69r3``
|
||||
/// - ``annotated(with:)-4qcem``
|
||||
/// - ``annotated(with:)-6ehs4``
|
||||
/// - ``annotatedWhenConnected(with:)``
|
||||
/// - ``select(_:)-270ge``
|
||||
/// - ``select(_:)-4jw13``
|
||||
/// - ``select(_:)-30yzl``
|
||||
/// - ``select(_:)-7e2y5``
|
||||
/// - ``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.
|
||||
///
|
||||
@@ -218,122 +209,6 @@ 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.
|
||||
@@ -346,17 +221,11 @@ extension SelectionRequest where Self: TypedRequest, Self.RowDecoder: TableRecor
|
||||
/// ### The WHERE and JOIN ON Clauses
|
||||
///
|
||||
/// - ``all()``
|
||||
/// - ``filter(_:)-7j0nw``
|
||||
/// - ``filter(_:)``
|
||||
/// - ``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.
|
||||
///
|
||||
@@ -441,34 +310,6 @@ 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
|
||||
@@ -481,7 +322,7 @@ extension FilteredRequest where Self: TypedRequest, Self.RowDecoder: TableRecord
|
||||
///
|
||||
/// ### Instance Methods
|
||||
///
|
||||
/// - ``aliased(_:)-3k5h4``
|
||||
/// - ``aliased(_:)``
|
||||
/// - ``TableAlias``
|
||||
///
|
||||
/// ### The WHERE Clause
|
||||
@@ -502,23 +343,11 @@ extension FilteredRequest where Self: TypedRequest, Self.RowDecoder: TableRecord
|
||||
/// ### 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.
|
||||
@@ -573,77 +402,7 @@ extension TableRequest where Self: TypedRequest {
|
||||
/// .filter(sql: "b.publishDate >= a.deathDate")
|
||||
/// .fetchAll(db)
|
||||
/// ```
|
||||
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)
|
||||
}
|
||||
func aliased(_ alias: TableAlias) -> Self
|
||||
}
|
||||
|
||||
extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
|
||||
@@ -964,26 +723,18 @@ extension TableRequest where Self: AggregatingRequest {
|
||||
///
|
||||
/// ### The GROUP BY Clause
|
||||
///
|
||||
/// - ``group(_:)-5soxm``
|
||||
/// - ``group(_:)-32exm``
|
||||
/// - ``group(_:)-edak``
|
||||
/// - ``group(_:)-4216o``
|
||||
/// - ``group(literal:)``
|
||||
/// - ``group(sql:arguments:)``
|
||||
/// - ``groupWhenConnected(_:)``
|
||||
///
|
||||
/// ### The HAVING Clause
|
||||
///
|
||||
/// - ``having(_:)-27hlo``
|
||||
/// - ``having(_:)``
|
||||
/// - ``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.
|
||||
///
|
||||
@@ -1174,71 +925,6 @@ 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.
|
||||
@@ -1247,21 +933,14 @@ extension AggregatingRequest where Self: TypedRequest, Self.RowDecoder: TableRec
|
||||
///
|
||||
/// ### The ORDER BY Clause
|
||||
///
|
||||
/// - ``order(_:)-5q7wj``
|
||||
/// - ``order(_:)-711zj``
|
||||
/// - ``order(_:)-63rzl``
|
||||
/// - ``order(_:)-6co0m``
|
||||
/// - ``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.
|
||||
///
|
||||
@@ -1299,15 +978,9 @@ 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(\.name)
|
||||
/// .order(Column("name"))
|
||||
/// .reversed()
|
||||
/// ```
|
||||
///
|
||||
@@ -1321,16 +994,12 @@ public protocol OrderedRequest {
|
||||
|
||||
/// Returns a request without any ordering.
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT * FROM player
|
||||
/// let request = Player.all()
|
||||
/// .order(\.name)
|
||||
/// .order(Column("name"))
|
||||
/// .unordered()
|
||||
/// ```
|
||||
func unordered() -> Self
|
||||
@@ -1423,74 +1092,6 @@ 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.
|
||||
@@ -1633,17 +1234,12 @@ extension JoinableRequest {
|
||||
/// For example, we can fetch only books whose author is French:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let countryCode = Column("countryCode")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Book: TableRecord, FetchableRecord {
|
||||
/// struct Author: TableRecord, FetchableRecord, Decodable { }
|
||||
/// struct Book: TableRecord, FetchableRecord, Decodable {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
///
|
||||
/// let frenchAuthors = Book.author.filter { $0.countryCode == "FR" }
|
||||
/// let frenchAuthors = Book.author.filter(Column("countryCode") == "FR")
|
||||
/// let bookInfos = try Book.all()
|
||||
/// .joining(required: frenchAuthors)
|
||||
/// .fetchAll(db)
|
||||
@@ -1660,19 +1256,9 @@ 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(\.color)
|
||||
/// let teamColor = Player.team.select(Column("color"))
|
||||
/// let request = Player.all().annotated(withOptional: teamColor)
|
||||
/// ```
|
||||
///
|
||||
@@ -1698,9 +1284,9 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
/// ``JoinableRequest/joining(optional:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let teamAlias = TableAlias<Team>()
|
||||
/// let teamAlias = TableAlias()
|
||||
/// let request = Player.all()
|
||||
/// .annotated(with: teamAlias.color)
|
||||
/// .annotated(with: teamAlias[Column("color")])
|
||||
/// .joining(optional: Player.team.aliased(teamAlias))
|
||||
/// ```
|
||||
public func annotated<A: Association>(withOptional association: A) -> Self where A.OriginRowDecoder == RowDecoder {
|
||||
@@ -1722,19 +1308,9 @@ 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(\.color)
|
||||
/// let teamColor = Player.team.select(Column("color"))
|
||||
/// let request = Player.all().annotated(withRequired: teamColor)
|
||||
/// ```
|
||||
///
|
||||
@@ -1760,9 +1336,9 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
/// ``JoinableRequest/joining(required:)``:
|
||||
///
|
||||
/// ```swift
|
||||
/// let teamAlias = TableAlias<Team>()
|
||||
/// let teamAlias = TableAlias()
|
||||
/// let request = Player.all()
|
||||
/// .annotated(with: teamAlias.color])
|
||||
/// .annotated(with: teamAlias[Column("color")])
|
||||
/// .joining(required: Player.team.aliased(teamAlias))
|
||||
/// ```
|
||||
public func annotated<A: Association>(withRequired association: A) -> Self where A.OriginRowDecoder == RowDecoder {
|
||||
@@ -1791,7 +1367,7 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
///
|
||||
/// ### Instance Methods
|
||||
///
|
||||
/// - ``TableRequest/aliased(_:)-3k5h4``
|
||||
/// - ``TableRequest/aliased(_:)``
|
||||
/// - ``TableAlias``
|
||||
///
|
||||
/// ### The WITH Clause
|
||||
@@ -1800,12 +1376,12 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
///
|
||||
/// ### The SELECT Clause
|
||||
///
|
||||
/// - ``SelectionRequest/annotated(with:)-9wodv``
|
||||
/// - ``SelectionRequest/annotated(with:)-69r3``
|
||||
/// - ``SelectionRequest/annotated(with:)-4qcem``
|
||||
/// - ``SelectionRequest/annotated(with:)-6ehs4``
|
||||
/// - ``SelectionRequest/annotatedWhenConnected(with:)``
|
||||
/// - ``distinct()``
|
||||
/// - ``SelectionRequest/select(_:)-270ge``
|
||||
/// - ``SelectionRequest/select(_:)-4jw13``
|
||||
/// - ``SelectionRequest/select(_:)-30yzl``
|
||||
/// - ``SelectionRequest/select(_:)-7e2y5``
|
||||
/// - ``SelectionRequest/select(literal:)``
|
||||
/// - ``SelectionRequest/select(sql:arguments:)``
|
||||
/// - ``SelectionRequest/selectWhenConnected(_:)``
|
||||
@@ -1813,7 +1389,7 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
/// ### The WHERE Clause
|
||||
///
|
||||
/// - ``FilteredRequest/all()``
|
||||
/// - ``FilteredRequest/filter(_:)-7j0nw``
|
||||
/// - ``FilteredRequest/filter(_:)``
|
||||
/// - ``TableRequest/filter(id:)``
|
||||
/// - ``TableRequest/filter(ids:)``
|
||||
/// - ``TableRequest/filter(key:)-1p9sq``
|
||||
@@ -1829,21 +1405,21 @@ extension JoinableRequest where Self: SelectionRequest {
|
||||
///
|
||||
/// ### The GROUP BY and HAVING Clauses
|
||||
///
|
||||
/// - ``AggregatingRequest/group(_:)-5soxm``
|
||||
/// - ``AggregatingRequest/group(_:)-32exm``
|
||||
/// - ``AggregatingRequest/group(_:)-edak``
|
||||
/// - ``AggregatingRequest/group(_:)-4216o``
|
||||
/// - ``AggregatingRequest/group(literal:)``
|
||||
/// - ``AggregatingRequest/group(sql:arguments:)``
|
||||
/// - ``TableRequest/groupByPrimaryKey()``
|
||||
/// - ``AggregatingRequest/groupWhenConnected(_:)``
|
||||
/// - ``AggregatingRequest/having(_:)-27hlo``
|
||||
/// - ``AggregatingRequest/having(_:)``
|
||||
/// - ``AggregatingRequest/having(literal:)``
|
||||
/// - ``AggregatingRequest/having(sql:arguments:)``
|
||||
/// - ``AggregatingRequest/havingWhenConnected(_:)``
|
||||
///
|
||||
/// ### The ORDER BY Clause
|
||||
///
|
||||
/// - ``OrderedRequest/order(_:)-5q7wj``
|
||||
/// - ``OrderedRequest/order(_:)-711zj``
|
||||
/// - ``OrderedRequest/order(_:)-63rzl``
|
||||
/// - ``OrderedRequest/order(_:)-6co0m``
|
||||
/// - ``OrderedRequest/order(literal:)``
|
||||
/// - ``OrderedRequest/order(sql:arguments:)``
|
||||
/// - ``OrderedRequest/orderWhenConnected(_:)``
|
||||
@@ -1874,23 +1450,6 @@ 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
|
||||
@@ -1900,17 +1459,11 @@ 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(\.name).distinct()
|
||||
/// let request = Player.select(Column("name")).distinct()
|
||||
/// ```
|
||||
func distinct() -> Self
|
||||
|
||||
@@ -1923,31 +1476,18 @@ public protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredReques
|
||||
/// latest message:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Chat: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let id = Column("id")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Message: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let date = Column("date")
|
||||
/// static let chatId = Column("chatId")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let latestMessageRequest = Message
|
||||
/// .annotated { max($0.date) }
|
||||
/// .group(\.chatId)
|
||||
/// .annotated(with: max(Column("date")))
|
||||
/// .group(Column("chatID"))
|
||||
///
|
||||
/// let latestMessageCTE = CommonTableExpression<Message>(
|
||||
/// let latestMessageCTE = CommonTableExpression(
|
||||
/// named: "latestMessage",
|
||||
/// request: latestMessageRequest)
|
||||
///
|
||||
/// let latestMessageAssociation = Chat.association(
|
||||
/// to: latestMessageCTE,
|
||||
/// on: { chat, latestMessage in
|
||||
/// chat.id == latestMessage.chatId
|
||||
/// chat[Column("id")] == latestMessage[Column("chatID")]
|
||||
/// })
|
||||
///
|
||||
/// // WITH latestMessage AS
|
||||
|
||||
@@ -39,18 +39,9 @@ extension ColumnExpression {
|
||||
/// SQL generated by the query interface.
|
||||
///
|
||||
/// For example, see how `Column("total").detached` makes it possible to
|
||||
/// sort this query:
|
||||
/// sort this query, when a raw `Column("total")` could not:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// static let team = belongsTo(Team.self)
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let bonus = Column("bonus")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT player.*,
|
||||
/// // (player.score + player.bonus) AS total,
|
||||
/// // team.*
|
||||
@@ -59,9 +50,9 @@ extension ColumnExpression {
|
||||
/// // ORDER BY total, player.name
|
||||
/// // ~~~~~
|
||||
/// let request = Player
|
||||
/// .annotated { ($0.score + $0.bonus).forKey("total") }
|
||||
/// .annotated(with: (Column("score") + Column("bonus")).forKey("total"))
|
||||
/// .including(required: Player.team)
|
||||
/// .order { [Column("total").detached, $0.name] }
|
||||
/// .order(Column("total").detached, Column("name"))
|
||||
/// ```
|
||||
public var detached: SQLExpression {
|
||||
SQL(sql: name.quotedDatabaseIdentifier).sqlExpression
|
||||
@@ -85,29 +76,14 @@ extension ColumnExpression where Self == Column {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: FetchableRecord, TableRecord {
|
||||
/// struct Player: TableRecord {
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// // DELETE FROM player WHERE score = 0
|
||||
/// try Player
|
||||
/// .filter { $0.score == 0 }
|
||||
/// .deleteAll(db)
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY score DESC LIMIT 10
|
||||
/// let bestPlayers = try Player
|
||||
/// .order(\.score)
|
||||
/// .limit(10)
|
||||
/// .fetchAll(db)
|
||||
///
|
||||
/// let maximumScore = try dbQueue.read { db in
|
||||
/// // SELECT MAX(score) FROM player
|
||||
/// let maximumScore = try Player
|
||||
/// .select({ max($0.score) }, as: Int.self)
|
||||
/// try Player
|
||||
/// .select(max(Column("score")), as: Int.self)
|
||||
/// .fetchOne(db)
|
||||
/// }
|
||||
/// ```
|
||||
@@ -147,13 +123,11 @@ extension Column: ColumnExpression { }
|
||||
|
||||
/// Support for column enums:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player {
|
||||
/// enum Columns: String, ColumnExpression {
|
||||
/// case id, name, score
|
||||
/// struct Player {
|
||||
/// enum Columns: String, ColumnExpression {
|
||||
/// case id, name, score
|
||||
/// }
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
extension ColumnExpression where Self: RawRepresentable, Self.RawValue == String {
|
||||
public var name: String { rawValue }
|
||||
}
|
||||
@@ -39,7 +39,7 @@ struct SQLCollection {
|
||||
|
||||
extension SQLCollection {
|
||||
/// Returns a qualified collection.
|
||||
func qualified(with alias: TableAliasBase) -> SQLCollection {
|
||||
func qualified(with alias: TableAlias) -> SQLCollection {
|
||||
switch impl {
|
||||
case .subquery,
|
||||
.table:
|
||||
|
||||
@@ -29,14 +29,8 @@
|
||||
/// SQL("DATE(\(value))").sqlExpression
|
||||
/// }
|
||||
///
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let createdAt = Column("createdAt")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM "player" WHERE DATE("createdAt") = '2020-01-23'
|
||||
/// let request = Player.filter { date($0.createdAt) == "2020-01-23" }
|
||||
/// let request = Player.filter(date(Column("createdAt")) == "2020-01-23")
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_expr.html>
|
||||
@@ -74,7 +68,7 @@ public struct SQLExpression: Sendable {
|
||||
///
|
||||
/// player.id
|
||||
/// player.name
|
||||
case qualifiedColumn(String, TableAliasBase)
|
||||
case qualifiedColumn(String, TableAlias)
|
||||
|
||||
/// A database value.
|
||||
///
|
||||
@@ -157,7 +151,7 @@ public struct SQLExpression: Sendable {
|
||||
/// A table full-text match.
|
||||
///
|
||||
/// <table> MATCH <pattern>
|
||||
indirect case tableMatch(TableAliasBase, SQLExpression)
|
||||
indirect case tableMatch(TableAlias, SQLExpression)
|
||||
|
||||
/// A logical `NOT` operator.
|
||||
///
|
||||
@@ -205,7 +199,7 @@ public struct SQLExpression: Sendable {
|
||||
/// player.id
|
||||
/// document.rowid
|
||||
/// country.code
|
||||
case qualifiedFastPrimaryKey(TableAliasBase)
|
||||
case qualifiedFastPrimaryKey(TableAlias)
|
||||
|
||||
/// An expression that is true iff the row exists:
|
||||
///
|
||||
@@ -213,10 +207,10 @@ public struct SQLExpression: Sendable {
|
||||
/// - For tables WITHOUT ROWID, it is true iff any primary key column is not null.
|
||||
/// - For views, it is true iff any column is not null.
|
||||
/// - For CTEs, it is not implemented yet.
|
||||
case qualifiedExists(TableAliasBase, isNegated: Bool)
|
||||
case qualifiedExists(TableAlias, isNegated: Bool)
|
||||
|
||||
/// Returns a qualified expression
|
||||
func qualified(with alias: TableAliasBase) -> Impl {
|
||||
func qualified(with alias: TableAlias) -> Impl {
|
||||
switch self {
|
||||
case .databaseValue,
|
||||
.qualifiedColumn,
|
||||
@@ -322,17 +316,12 @@ public struct SQLExpression: Sendable {
|
||||
/// Use it with the `joined(operator:)` method. For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// static let bonus = Column("bonus")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT score + bonus + 1000 FROM player
|
||||
/// let request = Player.select {
|
||||
/// [$0.score, $0.bonus, 1000.databaseValue].joined(operator: .add)
|
||||
/// }
|
||||
/// let values = [
|
||||
/// scoreColumn,
|
||||
/// bonusColumn,
|
||||
/// 1000.databaseValue]
|
||||
/// let request = Player.select(values.joined(operator: .add))
|
||||
/// ```
|
||||
public struct AssociativeBinaryOperator: Hashable, Sendable {
|
||||
/// The SQL operator
|
||||
@@ -648,7 +637,7 @@ extension SQLExpression {
|
||||
///
|
||||
/// player.id
|
||||
/// player.name
|
||||
static func qualifiedColumn(_ name: String, _ alias: TableAliasBase) -> Self {
|
||||
static func qualifiedColumn(_ name: String, _ alias: TableAlias) -> Self {
|
||||
self.init(impl: .qualifiedColumn(name, alias))
|
||||
}
|
||||
|
||||
@@ -871,7 +860,7 @@ extension SQLExpression {
|
||||
/// A table full-text match.
|
||||
///
|
||||
/// <table> MATCH <pattern>
|
||||
static func tableMatch(_ alias: TableAliasBase, _ expression: SQLExpression) -> Self {
|
||||
static func tableMatch(_ alias: TableAlias, _ expression: SQLExpression) -> Self {
|
||||
self.init(impl: .tableMatch(alias, expression))
|
||||
}
|
||||
|
||||
@@ -1159,7 +1148,7 @@ extension SQLExpression {
|
||||
/// player.id
|
||||
/// document.rowid
|
||||
/// country.code
|
||||
static func qualifiedFastPrimaryKey(_ alias: TableAliasBase) -> Self {
|
||||
static func qualifiedFastPrimaryKey(_ alias: TableAlias) -> Self {
|
||||
self.init(impl: .qualifiedFastPrimaryKey(alias))
|
||||
}
|
||||
|
||||
@@ -1169,7 +1158,7 @@ extension SQLExpression {
|
||||
/// - For tables WITHOUT ROWID, it is true iff any primary key column is not null.
|
||||
/// - For views, it is true iff any column is not null.
|
||||
/// - For CTEs, it is not implemented yet.
|
||||
static func qualifiedExists(_ alias: TableAliasBase) -> Self {
|
||||
static func qualifiedExists(_ alias: TableAlias) -> Self {
|
||||
self.init(impl: .qualifiedExists(alias, isNegated: false))
|
||||
}
|
||||
}
|
||||
@@ -1178,7 +1167,7 @@ extension SQLExpression {
|
||||
|
||||
extension SQLExpression {
|
||||
/// Returns a qualified expression
|
||||
func qualified(with alias: TableAliasBase) -> Self {
|
||||
func qualified(with alias: TableAlias) -> Self {
|
||||
.init(impl: impl.qualified(with: alias), preferredJSONInterpretation: preferredJSONInterpretation)
|
||||
}
|
||||
|
||||
@@ -1223,7 +1212,7 @@ extension SQLExpression {
|
||||
/// - parameter acceptsBijection: If true, expressions that define a
|
||||
/// bijection on a column return this column. For example: `-score`
|
||||
/// returns `score`.
|
||||
func column(_ db: Database, for alias: TableAliasBase, acceptsBijection: Bool = false) throws -> String? {
|
||||
func column(_ db: Database, for alias: TableAlias, acceptsBijection: Bool = false) throws -> String? {
|
||||
switch impl {
|
||||
case let .qualifiedColumn(name, a):
|
||||
if alias == a {
|
||||
@@ -1510,7 +1499,7 @@ extension SQLExpression {
|
||||
///
|
||||
/// // SELECT * FROM "player" WHERE "name" = 'Arthur' LIMIT 1
|
||||
/// try Player.filter(Column("name") == "Arthur").fetchOne(db)
|
||||
func identifyingColums(_ db: Database, for alias: TableAliasBase) throws -> Set<String> {
|
||||
func identifyingColums(_ db: Database, for alias: TableAlias) throws -> Set<String> {
|
||||
switch impl {
|
||||
case let .rowValue(expressions):
|
||||
assert(!expressions.isEmpty)
|
||||
@@ -1578,7 +1567,7 @@ extension SQLExpression {
|
||||
/// let request = Player.filter(keys: [1, 2, 3])
|
||||
/// let regionObservation = DatabaseRegionObservation(tracking: request)
|
||||
/// let valueObservation = ValueObservation.tracking(request.fetchAll)
|
||||
func identifyingRowIDs(_ db: Database, for alias: TableAliasBase) throws -> Set<Int64>? {
|
||||
func identifyingRowIDs(_ db: Database, for alias: TableAlias) throws -> Set<Int64>? {
|
||||
switch impl {
|
||||
case let .databaseValue(dbValue):
|
||||
if dbValue.isNull || dbValue == false.databaseValue {
|
||||
@@ -1985,7 +1974,7 @@ struct SQLSimpleFunctionInvocation {
|
||||
isPure && arguments.allSatisfy(\.isConstantInRequest)
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAliasBase) -> Self {
|
||||
func qualified(with alias: TableAlias) -> Self {
|
||||
SQLSimpleFunctionInvocation(
|
||||
name: name,
|
||||
arguments: arguments.map { $0.qualified(with: alias) },
|
||||
@@ -1993,7 +1982,7 @@ struct SQLSimpleFunctionInvocation {
|
||||
isJSONValue: isJSONValue)
|
||||
}
|
||||
|
||||
func column(_ db: Database, for alias: TableAliasBase) throws -> String? {
|
||||
func column(_ db: Database, for alias: TableAlias) throws -> String? {
|
||||
let name = name.uppercased()
|
||||
if ["HEX", "QUOTE"].contains(name) && arguments.count == 1 {
|
||||
return try arguments[0].column(db, for: alias, acceptsBijection: true)
|
||||
@@ -2029,7 +2018,7 @@ struct SQLAggregateFunctionInvocation {
|
||||
/// A false value does not provide any information.
|
||||
var isJSONValue: Bool
|
||||
|
||||
func qualified(with alias: TableAliasBase) -> Self {
|
||||
func qualified(with alias: TableAlias) -> Self {
|
||||
SQLAggregateFunctionInvocation(
|
||||
name: name,
|
||||
arguments: arguments.map { $0.qualified(with: alias) },
|
||||
@@ -2220,10 +2209,8 @@ extension SQLExpressible where Self == Column {
|
||||
/// - ``localizedLowercased``
|
||||
/// - ``localizedUppercased``
|
||||
/// - ``lowercased``
|
||||
/// - ``min(_:_:_:)``
|
||||
/// - ``min(_:)``
|
||||
/// - ``min(_:filter:)``
|
||||
/// - ``max(_:_:_:)``
|
||||
/// - ``max(_:)``
|
||||
/// - ``max(_:filter:)``
|
||||
/// - ``sum(_:)``
|
||||
@@ -2292,21 +2279,15 @@ extension Sequence where Element: SQLSpecificExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let isRegistered = Column("isRegistered")
|
||||
/// static let score = Column("score")
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// // WHERE (isRegistered
|
||||
/// // WHERE (registered
|
||||
/// // AND (score >= 1000)
|
||||
/// // AND (name IS NOT NULL))
|
||||
/// Player.filter {
|
||||
/// [$0.isRegistered, $0.score >= 1000, $0.name != nil].joined(operator: .and)
|
||||
/// }
|
||||
/// let conditions = [
|
||||
/// Column("registered"),
|
||||
/// Column("score") >= 1000,
|
||||
/// Column("name") != nil]
|
||||
/// Player.filter(conditions.joined(operator: .and))
|
||||
/// ```
|
||||
///
|
||||
/// When the sequence is empty, `joined(operator:)` returns the neutral
|
||||
@@ -2329,21 +2310,15 @@ extension Sequence where Element == any SQLSpecificExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let isRegistered = Column("isRegistered")
|
||||
/// static let score = Column("score")
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// // WHERE (isRegistered
|
||||
/// // WHERE (registered
|
||||
/// // AND (score >= 1000)
|
||||
/// // AND (name IS NOT NULL))
|
||||
/// Player.filter {
|
||||
/// [$0.isRegistered, $0.score >= 1000, $0.name != nil].joined(operator: .and)
|
||||
/// }
|
||||
/// let conditions = [
|
||||
/// Column("registered"),
|
||||
/// Column("score") >= 1000,
|
||||
/// Column("name") != nil]
|
||||
/// Player.filter(conditions.joined(operator: .and))
|
||||
/// ```
|
||||
///
|
||||
/// When the sequence is empty, `joined(operator:)` returns the neutral
|
||||
@@ -2406,17 +2381,9 @@ extension SQLSpecificExpressible {
|
||||
/// 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.select {
|
||||
/// ($0.score * $0.bonus).forKey("totalScore")
|
||||
/// }
|
||||
/// let totalScore = (Column("score") * Column("bonus")).forKey("totalScore")
|
||||
/// let request = Player.select(totalScore)
|
||||
/// ```
|
||||
///
|
||||
/// If you need to refer to the aliased column in another part of a request,
|
||||
@@ -2427,9 +2394,7 @@ extension SQLSpecificExpressible {
|
||||
/// // FROM player
|
||||
/// // ORDER BY totalScore
|
||||
/// let request = Player
|
||||
/// .select {
|
||||
/// ($0.score * $0.bonus).forKey("totalScore")
|
||||
/// }
|
||||
/// .select(totalScore)
|
||||
/// .order(Column("totalScore").detached)
|
||||
/// ```
|
||||
public func forKey(_ key: String) -> SQLSelection {
|
||||
@@ -2453,17 +2418,9 @@ extension SQLSpecificExpressible {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let email = Column("email")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT * FROM player
|
||||
/// // WHERE email = 'contact@example.com' COLLATE NOCASE
|
||||
/// Player.filter {
|
||||
/// $0.email.collating(.nocase) == "contact@example.com"
|
||||
/// }
|
||||
/// Player.filter(Column("email").collating(.nocase) == "contact@example.com")
|
||||
/// ```
|
||||
public func collating(_ collation: Database.CollationName) -> SQLExpression {
|
||||
.collated(sqlExpression, collation)
|
||||
|
||||
@@ -11,7 +11,7 @@ public func abs(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `AVG` SQL aggregate function.
|
||||
/// The `AVG` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -26,7 +26,7 @@ public func average(
|
||||
.aggregateFunction("AVG", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `AVG` SQL aggregate function.
|
||||
/// The `AVG` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -44,7 +44,7 @@ public func average(
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `AVG` SQL aggregate function.
|
||||
/// The `AVG` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -147,24 +147,8 @@ public func length(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
.function("LENGTH", [value.sqlExpression])
|
||||
}
|
||||
|
||||
/// The `MAX` SQL multi-argument function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // MAX(score, 1000)
|
||||
/// max(Column("score"), 1000)
|
||||
/// ```
|
||||
public func max(
|
||||
_ value1: any SQLSpecificExpressible,
|
||||
_ value2: any SQLExpressible,
|
||||
_ values: any SQLExpressible...
|
||||
) -> SQLExpression {
|
||||
.simpleFunction("MAX", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `MAX` SQL aggregate function.
|
||||
/// The `MAX` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -179,7 +163,7 @@ public func max(
|
||||
.aggregateFunction("MAX", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `MAX` SQL aggregate function.
|
||||
/// The `MAX` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -195,7 +179,7 @@ public func max(
|
||||
.aggregateFunction("MAX", [value.sqlExpression], filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `MAX` SQL aggregate function.
|
||||
/// The `MAX` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -208,24 +192,8 @@ public func max(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// The `MIN` SQL multi-argument function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // MIN(score, 1000)
|
||||
/// min(Column("score"), 1000)
|
||||
/// ```
|
||||
public func min(
|
||||
_ value1: any SQLSpecificExpressible,
|
||||
_ value2: any SQLExpressible,
|
||||
_ values: any SQLExpressible...
|
||||
) -> SQLExpression {
|
||||
.simpleFunction("MIN", [value1.sqlExpression, value2.sqlExpression] + values.map(\.sqlExpression))
|
||||
}
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `MIN` SQL aggregate function.
|
||||
/// The `MIN` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -240,7 +208,7 @@ public func min(
|
||||
.aggregateFunction("MIN", [value.sqlExpression], filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `MIN` SQL aggregate function.
|
||||
/// The `MIN` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -256,7 +224,7 @@ public func min(
|
||||
.aggregateFunction("MIN", [value.sqlExpression], filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `MIN` SQL aggregate function.
|
||||
/// The `MIN` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -270,7 +238,7 @@ public func min(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `SUM` SQL aggregate function.
|
||||
/// The `SUM` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -294,7 +262,7 @@ public func sum(
|
||||
filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `SUM` SQL aggregate function.
|
||||
/// The `SUM` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -316,7 +284,7 @@ public func sum(
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `SUM` SQL aggregate function.
|
||||
/// The `SUM` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -334,7 +302,7 @@ public func sum(_ value: some SQLSpecificExpressible) -> SQLExpression {
|
||||
#endif
|
||||
|
||||
#if GRDBCUSTOMSQLITE || GRDBCIPHER
|
||||
/// The `TOTAL` SQL aggregate function.
|
||||
/// The `TOTAL` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -358,7 +326,7 @@ public func total(
|
||||
filter: filter?.sqlExpression)
|
||||
}
|
||||
#else
|
||||
/// The `TOTAL` SQL aggregate function.
|
||||
/// The `TOTAL` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
@@ -380,7 +348,7 @@ public func total(
|
||||
filter: filter.sqlExpression)
|
||||
}
|
||||
|
||||
/// The `TOTAL` SQL aggregate function.
|
||||
/// The `TOTAL` SQL function.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
|
||||
@@ -86,7 +86,7 @@ extension SQLOrdering {
|
||||
}
|
||||
|
||||
extension SQLOrdering {
|
||||
func qualified(with alias: TableAliasBase) -> SQLOrdering {
|
||||
func qualified(with alias: TableAlias) -> SQLOrdering {
|
||||
switch impl {
|
||||
case .expression(let expression):
|
||||
return .expression(expression.qualified(with: alias))
|
||||
|
||||
@@ -282,6 +282,12 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
func unlimited() -> Self {
|
||||
with {
|
||||
$0.limit = nil
|
||||
}
|
||||
}
|
||||
|
||||
func withStableOrder() -> Self {
|
||||
with { relation in
|
||||
relation.ordering = relation.ordering.appending(Ordering(orderings: { [relation] db in
|
||||
@@ -331,7 +337,7 @@ extension SQLRelation: Refinable {
|
||||
}
|
||||
}
|
||||
|
||||
func aliased(_ alias: TableAliasBase) -> Self {
|
||||
func aliased(_ alias: TableAlias) -> Self {
|
||||
with {
|
||||
$0.source = $0.source.aliased(alias)
|
||||
}
|
||||
@@ -655,6 +661,47 @@ extension SQLRelation {
|
||||
}
|
||||
}
|
||||
|
||||
extension SQLRelation {
|
||||
#warning("TODO: the order clause may refer to stuff inside the CTE.")
|
||||
#warning("TODO: Try to leave the ordering inside the CTE")
|
||||
func asCommonTableExpression(named tableName: String) -> Self {
|
||||
with { relation in
|
||||
GRDBPrecondition(ctes[tableName] == nil, """
|
||||
Can't turn relation into a Common Table Expression because \
|
||||
CTE '\(tableName)' is already defined. Please file a bug \
|
||||
at https://github.com/groue/GRDB.swift/issues/new
|
||||
""")
|
||||
|
||||
relation.ctes[tableName] = SQLCTE(
|
||||
tableName: tableName,
|
||||
columns: nil,
|
||||
sqlSubquery: .relation(
|
||||
self
|
||||
.unorderedUnlessLimited() // only preserve ordering in the CTE if limited
|
||||
.removingPrefetchedAssociations()),
|
||||
isRecursive: false)
|
||||
|
||||
relation.source = SQLSource(
|
||||
tableName: tableName,
|
||||
associationOriginTable: relation.source.associationOriginTable ?? relation.source.tableName)
|
||||
|
||||
relation.selectionPromise = DatabasePromise { _ in [.allColumns] }
|
||||
relation.filterPromise = nil
|
||||
relation.isDistinct = false
|
||||
relation.groupPromise = nil
|
||||
relation.havingExpressionPromise = nil
|
||||
relation.limit = nil
|
||||
|
||||
relation = relation.filteringChildren { child in
|
||||
switch child.kind {
|
||||
case .all, .bridge: true
|
||||
case .oneOptional, .oneRequired: false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SQLLimit
|
||||
|
||||
struct SQLLimit {
|
||||
@@ -673,10 +720,16 @@ struct SQLLimit {
|
||||
// MARK: - SQLSource
|
||||
|
||||
struct SQLSource: Sendable {
|
||||
/// The name of a database table to select from.
|
||||
var tableName: String
|
||||
var alias: TableAliasBase?
|
||||
var alias: TableAlias?
|
||||
|
||||
func aliased(_ alias: TableAliasBase) -> SQLSource {
|
||||
/// When not nil, use this table name instead of `tableName` when looking
|
||||
/// for foreign keys on this source. This string is not nil when an
|
||||
/// `SQLRelation` has been turned into a common table expression.
|
||||
var associationOriginTable: String?
|
||||
|
||||
func aliased(_ alias: TableAlias) -> SQLSource {
|
||||
if let sourceAlias = self.alias {
|
||||
alias.becomeProxy(of: sourceAlias)
|
||||
return self
|
||||
@@ -705,7 +758,7 @@ extension SQLRelation {
|
||||
}
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAliasBase) -> Element {
|
||||
func qualified(with alias: TableAlias) -> Element {
|
||||
switch self {
|
||||
case .terms(let terms):
|
||||
return .terms(terms.map { $0.map { $0.qualified(with: alias) } })
|
||||
@@ -752,7 +805,7 @@ extension SQLRelation {
|
||||
isReversed: !isReversed)
|
||||
}
|
||||
|
||||
func qualified(with alias: TableAliasBase) -> Ordering {
|
||||
func qualified(with alias: TableAlias) -> Ordering {
|
||||
Ordering(
|
||||
elements: elements.map { $0.qualified(with: alias) },
|
||||
isReversed: isReversed)
|
||||
@@ -814,7 +867,7 @@ enum SQLAssociationCondition: Sendable {
|
||||
/// player[Column("id")] == bonus[Column("playerID")]
|
||||
/// })
|
||||
/// Player.with(bonus).joining(required: association)
|
||||
case expression(@Sendable (_ left: TableAliasBase, _ right: TableAliasBase) -> SQLExpression?)
|
||||
case expression(@Sendable (_ left: TableAlias, _ right: TableAlias) -> SQLExpression?)
|
||||
|
||||
/// The condition that does not constrain the two associated tables
|
||||
/// in any way.
|
||||
@@ -831,8 +884,8 @@ enum SQLAssociationCondition: Sendable {
|
||||
|
||||
func joinExpression(
|
||||
_ db: Database,
|
||||
leftAlias: TableAliasBase,
|
||||
rightAlias: TableAliasBase)
|
||||
leftAlias: TableAlias,
|
||||
rightAlias: TableAlias)
|
||||
throws -> SQLExpression?
|
||||
{
|
||||
switch self {
|
||||
@@ -999,7 +1052,7 @@ extension JoinMapping {
|
||||
/// JOIN operator.
|
||||
/// - parameter rightAlias: A TableAlias for the table on the right of the
|
||||
/// JOIN operator.
|
||||
func joinExpression(leftAlias: TableAliasBase, rightAlias: TableAliasBase) -> SQLExpression {
|
||||
func joinExpression(leftAlias: TableAlias, rightAlias: TableAlias) -> SQLExpression {
|
||||
map { rightAlias[$0.right] == leftAlias[$0.left] }.joined(operator: .and)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,13 +24,13 @@ public struct SQLSelection: Sendable {
|
||||
case allColumns
|
||||
|
||||
/// All columns, qualified: `player.*`
|
||||
case qualifiedAllColumns(TableAliasBase)
|
||||
case qualifiedAllColumns(TableAlias)
|
||||
|
||||
/// All columns but the specified ones
|
||||
case allColumnsExcluding(Set<CaseInsensitiveIdentifier>)
|
||||
|
||||
/// All columns but the specified ones, qualified.
|
||||
case qualifiedAllColumnsExcluding(TableAliasBase, Set<CaseInsensitiveIdentifier>)
|
||||
case qualifiedAllColumnsExcluding(TableAlias, Set<CaseInsensitiveIdentifier>)
|
||||
|
||||
/// An expression
|
||||
case expression(SQLExpression)
|
||||
@@ -53,15 +53,12 @@ public struct SQLSelection: Sendable {
|
||||
}
|
||||
|
||||
/// All columns, qualified: `player.*`
|
||||
static func qualifiedAllColumns(_ alias: TableAliasBase) -> Self {
|
||||
static func qualifiedAllColumns(_ alias: TableAlias) -> Self {
|
||||
self.init(impl: .qualifiedAllColumns(alias))
|
||||
}
|
||||
|
||||
/// All columns but the specified ones, qualified.
|
||||
static func qualifiedAllColumnsExcluding(
|
||||
_ alias: TableAliasBase,
|
||||
_ excludedColumns: Set<CaseInsensitiveIdentifier>
|
||||
) -> Self {
|
||||
static func qualifiedAllColumnsExcluding(_ alias: TableAlias, _ excludedColumns: Set<CaseInsensitiveIdentifier>) -> Self {
|
||||
self.init(impl: .qualifiedAllColumnsExcluding(alias, excludedColumns))
|
||||
}
|
||||
|
||||
@@ -261,7 +258,7 @@ extension SQLSelection {
|
||||
}
|
||||
|
||||
/// Returns a qualified selection
|
||||
func qualified(with alias: TableAliasBase) -> SQLSelection {
|
||||
func qualified(with alias: TableAlias) -> SQLSelection {
|
||||
switch impl {
|
||||
case .qualifiedAllColumns, .qualifiedAllColumnsExcluding:
|
||||
return self
|
||||
|
||||
@@ -48,8 +48,6 @@
|
||||
///
|
||||
/// ### Updating Rows
|
||||
///
|
||||
/// - ``updateAll(_:onConflict:assignment:)``
|
||||
/// - ``updateAll(_:onConflict:assignments:)``
|
||||
/// - ``updateAll(_:onConflict:_:)-4w9b``
|
||||
/// - ``updateAll(_:onConflict:_:)-4cvap``
|
||||
///
|
||||
@@ -58,8 +56,7 @@
|
||||
/// `Table` provide convenience access to most ``DerivableRequest`` and
|
||||
/// ``QueryInterfaceRequest`` methods.
|
||||
///
|
||||
/// - ``aliased(_:)-3135k``
|
||||
/// - ``aliased(_:)-5dkyd``
|
||||
/// - ``aliased(_:)``
|
||||
/// - ``all()``
|
||||
/// - ``annotated(with:)-6i101``
|
||||
/// - ``annotated(with:)-6x399``
|
||||
@@ -457,7 +454,7 @@ extension Table {
|
||||
/// let ids = try table.selectPrimaryKey(as: Int64.self).fetchSet(db)
|
||||
/// ```
|
||||
public func selectID() -> QueryInterfaceRequest<RowDecoder.ID>
|
||||
where RowDecoder: Identifiable & SendableMetatype
|
||||
where RowDecoder: Identifiable
|
||||
{
|
||||
all().selectID()
|
||||
}
|
||||
@@ -743,23 +740,11 @@ extension Table {
|
||||
all().limit(limit, offset: offset)
|
||||
}
|
||||
|
||||
/// Returns a request that can be referred to with the provided
|
||||
/// anonymous alias.
|
||||
/// Returns a request that can be referred to with the provided alias.
|
||||
///
|
||||
/// `table.aliased(alias)` is equivalent to `table.all().aliased(alias)`.
|
||||
///
|
||||
/// See ``TableRequest/aliased(_:)-772vb`` for more information.
|
||||
public func aliased(_ alias: TableAlias<Void>) -> QueryInterfaceRequest<RowDecoder> {
|
||||
all().aliased(alias)
|
||||
}
|
||||
|
||||
/// Returns a request that can be referred to with the provided
|
||||
/// record alias.
|
||||
///
|
||||
/// `table.aliased(alias)` is equivalent to `table.all().aliased(alias)`.
|
||||
///
|
||||
/// See ``TableRequest/aliased(_:)-3k5h4`` for more information.
|
||||
public func aliased(_ alias: TableAlias<RowDecoder>) -> QueryInterfaceRequest<RowDecoder> {
|
||||
/// See ``TableRequest/aliased(_:)`` for more information.
|
||||
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest<RowDecoder> {
|
||||
all().aliased(alias)
|
||||
}
|
||||
|
||||
@@ -1345,17 +1330,12 @@ extension Table {
|
||||
/// - returns: An association to the common table expression.
|
||||
public func association<Destination>(
|
||||
to cte: CommonTableExpression<Destination>,
|
||||
on condition: @escaping @Sendable (
|
||||
_ left: TableAlias<RowDecoder>,
|
||||
_ right: TableAlias<Destination>
|
||||
) -> any SQLExpressible)
|
||||
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
-> JoinAssociation<RowDecoder, Destination>
|
||||
{
|
||||
JoinAssociation(
|
||||
to: cte.relationForAll,
|
||||
condition: .expression { left, right in
|
||||
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
|
||||
})
|
||||
condition: .expression { condition($0, $1).sqlExpression })
|
||||
}
|
||||
|
||||
/// Creates an association to a common table expression.
|
||||
@@ -1904,77 +1884,6 @@ extension Table {
|
||||
// MARK: - Batch Update
|
||||
|
||||
extension Table {
|
||||
/// Updates all rows, and returns the number of updated rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let playerTable = Table<Player>("player")
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = 0
|
||||
/// try playerTable.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 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,
|
||||
assignment: (DatabaseComponents) throws -> ColumnAssignment
|
||||
) throws -> Int
|
||||
where RowDecoder: TableRecord
|
||||
{
|
||||
try updateAll(db, onConflict: conflictResolution, [assignment(RowDecoder.databaseComponents)])
|
||||
}
|
||||
|
||||
/// Updates all rows, and returns the number of updated rows.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let playerTable = Table<Player>("player")
|
||||
///
|
||||
/// try dbQueue.write { db in
|
||||
/// // UPDATE player SET score = 0
|
||||
/// try playerTable.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 all rows, and returns the number of updated rows.
|
||||
///
|
||||
/// For example:
|
||||
@@ -2031,7 +1940,3 @@ extension Table {
|
||||
try updateAll(db, onConflict: conflictResolution, assignments)
|
||||
}
|
||||
}
|
||||
|
||||
extension Table where RowDecoder: TableRecord {
|
||||
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
|
||||
}
|
||||
@@ -37,8 +37,8 @@ final class SQLGenerationContext {
|
||||
}
|
||||
}
|
||||
|
||||
private let resolvedNames: [TableAliasBase: String]
|
||||
private let ownAliases: Set<TableAliasBase>
|
||||
private let resolvedNames: [TableAlias: String]
|
||||
private let ownAliases: Set<TableAlias>
|
||||
private let ownCTEs: [String: SQLCTE]
|
||||
|
||||
/// Creates a generation context.
|
||||
@@ -50,7 +50,7 @@ final class SQLGenerationContext {
|
||||
init(
|
||||
_ db: Database,
|
||||
argumentsSink: StatementArgumentsSink = StatementArgumentsSink(),
|
||||
aliases: [TableAliasBase] = [],
|
||||
aliases: [TableAlias] = [],
|
||||
ctes: OrderedDictionary<String, SQLCTE> = [:])
|
||||
{
|
||||
self.parent = .none(db: db, argumentsSink: argumentsSink)
|
||||
@@ -66,7 +66,7 @@ final class SQLGenerationContext {
|
||||
/// - parameter ctes: An dictionary of available CTEs.
|
||||
private init(
|
||||
parent: SQLGenerationContext,
|
||||
aliases: [TableAliasBase],
|
||||
aliases: [TableAlias],
|
||||
ctes: OrderedDictionary<String, SQLCTE>)
|
||||
{
|
||||
self.parent = .context(parent)
|
||||
@@ -77,7 +77,7 @@ final class SQLGenerationContext {
|
||||
|
||||
/// Returns a generation context suitable for subqueries.
|
||||
func subqueryContext(
|
||||
aliases: [TableAliasBase] = [],
|
||||
aliases: [TableAlias] = [],
|
||||
ctes: OrderedDictionary<String, SQLCTE> = [:]) -> SQLGenerationContext
|
||||
{
|
||||
SQLGenerationContext(parent: self, aliases: aliases, ctes: ctes)
|
||||
@@ -118,7 +118,7 @@ final class SQLGenerationContext {
|
||||
///
|
||||
/// WHERE column == 1
|
||||
/// SELECT *
|
||||
func qualifier(for alias: TableAliasBase) -> String? {
|
||||
func qualifier(for alias: TableAlias) -> String? {
|
||||
if alias.hasUserName {
|
||||
return alias.identityName
|
||||
}
|
||||
@@ -132,7 +132,7 @@ final class SQLGenerationContext {
|
||||
}
|
||||
|
||||
/// WHERE <resolvedName> MATCH pattern
|
||||
func resolvedName(for alias: TableAliasBase) -> String {
|
||||
func resolvedName(for alias: TableAlias) -> String {
|
||||
if let name = resolvedNames[alias] {
|
||||
return name
|
||||
}
|
||||
@@ -145,7 +145,7 @@ final class SQLGenerationContext {
|
||||
}
|
||||
|
||||
/// FROM tableName <alias>
|
||||
func aliasName(for alias: TableAliasBase) -> String? {
|
||||
func aliasName(for alias: TableAlias) -> String? {
|
||||
let resolvedName = self.resolvedName(for: alias)
|
||||
if resolvedName != alias.tableName {
|
||||
return resolvedName
|
||||
@@ -244,9 +244,318 @@ class StatementArgumentsSink {
|
||||
}
|
||||
}
|
||||
|
||||
extension [TableAliasBase] {
|
||||
// MARK: - TableAlias
|
||||
|
||||
/// A TableAlias identifies a table in a request.
|
||||
///
|
||||
/// See ``TableRequest/aliased(_:)`` for more information and examples.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
public class TableAlias: @unchecked Sendable {
|
||||
// This Sendable conformance is transient. TableAlias IS NOT really Sendable.
|
||||
// TODO: GRDB7 Make TableAlias really Sendable
|
||||
private enum Impl {
|
||||
/// A TableAlias is undefined when it is created by the GRDB user:
|
||||
///
|
||||
/// let alias = TableAlias()
|
||||
/// let alias = TableAlias(name: "custom")
|
||||
case undefined(userName: String?)
|
||||
|
||||
/// A TableAlias is a table when explicitly specified:
|
||||
///
|
||||
/// let alias = TableAlias(tableName: "player")
|
||||
///
|
||||
/// Or when it qualifies a request that wasn't qualified yet (in which
|
||||
/// case it turns from undefined to a table):
|
||||
///
|
||||
/// // SELECT custom.* FROM player custom
|
||||
/// let alias = TableAlias(name: "custom")
|
||||
/// let request = Player.all().aliased(alias)
|
||||
case table(tableName: String, userName: String?)
|
||||
|
||||
/// A TableAlias can be a proxy for another table alias. Two different
|
||||
/// instances for the same table identifier:
|
||||
///
|
||||
/// // Pointless example: make alias2 a proxy for alias1
|
||||
/// let alias1 = TableAlias()
|
||||
/// let alias2 = TableAlias()
|
||||
/// Player.all()
|
||||
/// .aliased(alias1)
|
||||
/// .aliased(alias2)
|
||||
///
|
||||
/// Proxies are useful because queries get implicit aliases as soon
|
||||
/// as they are joined with associations. In the example below,
|
||||
/// customAlias becomes a proxy for the request's implicit alias, which
|
||||
/// gets a custom name. This allows implicit and user aliases to merge
|
||||
/// into a single "table identifier" that matches the user's expectations:
|
||||
///
|
||||
/// // SELECT custom.*, team.*
|
||||
/// // FROM player custom
|
||||
/// // JOIN team ON taem.id = custom.teamId
|
||||
/// // WHERE custom.name = 'Arthur'
|
||||
/// let customAlias = TableAlias(name: "custom")
|
||||
/// let request = Player
|
||||
/// .including(required: Player.team)
|
||||
/// .filter(sql: "custom.name = 'Arthur'")
|
||||
/// .aliased(customAlias)
|
||||
case proxy(TableAlias)
|
||||
}
|
||||
|
||||
private var impl: Impl
|
||||
|
||||
/// Resolve all proxies
|
||||
private var root: TableAlias {
|
||||
if case .proxy(let base) = impl {
|
||||
return base.root
|
||||
} else {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// exposed to SQLGenerationContext
|
||||
fileprivate var identityName: String {
|
||||
userName ?? tableName
|
||||
}
|
||||
|
||||
// exposed to SQLGenerationContext
|
||||
fileprivate var hasUserName: Bool {
|
||||
userName != nil
|
||||
}
|
||||
|
||||
var tableName: String {
|
||||
switch impl {
|
||||
case .undefined:
|
||||
// Likely a GRDB bug
|
||||
fatalError("Undefined alias has no table name")
|
||||
case .table(tableName: let tableName, userName: _):
|
||||
return tableName
|
||||
case .proxy(let base):
|
||||
return base.tableName
|
||||
}
|
||||
}
|
||||
|
||||
private var userName: String? {
|
||||
switch impl {
|
||||
case .undefined(let userName):
|
||||
return userName
|
||||
case .table(tableName: _, userName: let userName):
|
||||
return userName
|
||||
case .proxy(let base):
|
||||
return base.userName
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a TableAlias.
|
||||
///
|
||||
/// When the alias is given a name, this name is guaranteed to be used as
|
||||
/// the table alias in the SQL query:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT p.* FROM player p
|
||||
/// let alias = TableAlias(name: "p")
|
||||
/// let request = Player.all().aliased(alias)
|
||||
/// ```
|
||||
public init(name: String? = nil) {
|
||||
self.impl = .undefined(userName: name)
|
||||
}
|
||||
|
||||
init(tableName: String, userName: String? = nil) {
|
||||
self.impl = .table(tableName: tableName, userName: userName)
|
||||
}
|
||||
|
||||
func becomeProxy(of base: TableAlias) {
|
||||
if self === base {
|
||||
return
|
||||
}
|
||||
|
||||
switch impl {
|
||||
case let .undefined(userName):
|
||||
if let userName {
|
||||
// rename
|
||||
assert(base.userName == nil || base.userName == userName)
|
||||
base.setUserName(userName)
|
||||
}
|
||||
self.impl = .proxy(base)
|
||||
case let .table(tableName: tableName, userName: userName):
|
||||
assert(tableName == base.tableName)
|
||||
if let userName {
|
||||
// rename
|
||||
assert(base.userName == nil || base.userName == userName)
|
||||
base.setUserName(userName)
|
||||
}
|
||||
self.impl = .proxy(base)
|
||||
case let .proxy(selfBase):
|
||||
selfBase.becomeProxy(of: base)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns nil if aliases can't be merged (conflict in tables, aliases...)
|
||||
func merged(with other: TableAlias) -> TableAlias? {
|
||||
if self === other {
|
||||
return self
|
||||
}
|
||||
|
||||
let root = self.root
|
||||
let otherRoot = other.root
|
||||
switch (root.impl, otherRoot.impl) {
|
||||
case let (.table(tableName: tableName, userName: userName),
|
||||
.table(tableName: otherTableName, userName: otherUserName)):
|
||||
guard tableName == otherTableName else {
|
||||
// can't merge
|
||||
return nil
|
||||
}
|
||||
if let userName, let otherUserName, userName != otherUserName {
|
||||
// can't merge
|
||||
return nil
|
||||
}
|
||||
root.becomeProxy(of: otherRoot)
|
||||
return otherRoot
|
||||
default:
|
||||
// can't merge
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private func setUserName(_ userName: String) {
|
||||
switch impl {
|
||||
case .undefined:
|
||||
self.impl = .undefined(userName: userName)
|
||||
case .table(tableName: let tableName, userName: _):
|
||||
self.impl = .table(tableName: tableName, userName: userName)
|
||||
case .proxy(let base):
|
||||
base.setUserName(userName)
|
||||
}
|
||||
}
|
||||
|
||||
func setTableName(_ tableName: String) {
|
||||
switch impl {
|
||||
case .undefined(let userName):
|
||||
self.impl = .table(tableName: tableName, userName: userName)
|
||||
case .table(tableName: let initialTableName, userName: _):
|
||||
// It is a programmer error to reuse the same TableAlias for
|
||||
// multiple tables.
|
||||
//
|
||||
// // Don't do that
|
||||
// let alias = TableAlias()
|
||||
// let books = Book.aliased(alias)...
|
||||
// let authors = Author.aliased(alias)...
|
||||
GRDBPrecondition(
|
||||
tableName.lowercased() == initialTableName.lowercased(),
|
||||
"A TableAlias most not be used to refer to multiple tables")
|
||||
case .proxy(let base):
|
||||
base.setTableName(tableName)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a result column that refers to the aliased table.
|
||||
public subscript(_ selectable: some SQLSelectable) -> SQLSelection {
|
||||
// TODO: test
|
||||
selectable.sqlSelection.qualified(with: self)
|
||||
}
|
||||
|
||||
/// Returns an SQL expression that refers to the aliased table.
|
||||
///
|
||||
/// For example, let's sort 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()
|
||||
/// let request = Book
|
||||
/// .joining(required: Book.author.aliased(authorAlias))
|
||||
/// .order(authorAlias[Column("name")], Column("title"))
|
||||
/// ```
|
||||
public subscript(_ expression: some SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression {
|
||||
expression.sqlExpression.qualified(with: self)
|
||||
}
|
||||
|
||||
public subscript(_ expression: some SQLJSONExpressible &
|
||||
SQLSpecificExpressible &
|
||||
SQLSelectable &
|
||||
SQLOrderingTerm)
|
||||
-> AnySQLJSONExpressible
|
||||
{
|
||||
AnySQLJSONExpressible(sqlExpression: expression.sqlExpression.qualified(with: self))
|
||||
}
|
||||
|
||||
/// Returns an SQL ordering term that refers to the aliased table.
|
||||
///
|
||||
/// For example, let's sort 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 ASC, book.title ASC
|
||||
/// let authorAlias = TableAlias()
|
||||
/// let request = Book
|
||||
/// .joining(required: Book.author.aliased(authorAlias))
|
||||
/// .order(authorAlias[Column("name").asc], Column("title").asc)
|
||||
/// ```
|
||||
public subscript(_ ordering: some SQLOrderingTerm) -> SQLOrdering {
|
||||
ordering.sqlOrdering.qualified(with: self)
|
||||
}
|
||||
|
||||
/// Returns an SQL column that refers to the aliased table.
|
||||
///
|
||||
/// For example, let's sort 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()
|
||||
/// let request = Book
|
||||
/// .joining(required: Book.author.aliased(authorAlias))
|
||||
/// .order(authorAlias["name"], Column("title"))
|
||||
/// ```
|
||||
public subscript(_ column: String) -> SQLExpression {
|
||||
.qualifiedColumn(column, self)
|
||||
}
|
||||
|
||||
/// A boolean SQL expression indicating whether this alias refers to some
|
||||
/// rows, or not.
|
||||
///
|
||||
/// In the example below, we only fetch books that are not associated to
|
||||
/// any author:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord, FetchableRecord { }
|
||||
/// struct Book: TableRecord, FetchableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let authorAlias = TableAlias()
|
||||
/// let request = Book
|
||||
/// .joining(optional: Book.author.aliased(authorAlias))
|
||||
/// .filter(!authorAlias.exists)
|
||||
/// let books = try request.fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
public var exists: SQLExpression {
|
||||
SQLExpression.qualifiedExists(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TableAlias: Equatable {
|
||||
public static func == (lhs: TableAlias, rhs: TableAlias) -> Bool {
|
||||
ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root)
|
||||
}
|
||||
}
|
||||
|
||||
extension TableAlias: Hashable {
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(ObjectIdentifier(root))
|
||||
}
|
||||
}
|
||||
|
||||
extension [TableAlias] {
|
||||
/// Resolve ambiguities in aliases' names.
|
||||
fileprivate var resolvedNames: [TableAliasBase: String] {
|
||||
fileprivate var resolvedNames: [TableAlias: String] {
|
||||
// It is a programmer error to reuse the same TableAlias for
|
||||
// multiple tables.
|
||||
//
|
||||
@@ -262,7 +571,7 @@ extension [TableAliasBase] {
|
||||
}
|
||||
|
||||
var uniqueLowercaseNames: Set<String> = []
|
||||
var ambiguousGroups: [[TableAliasBase]] = []
|
||||
var ambiguousGroups: [[TableAlias]] = []
|
||||
|
||||
for (lowercaseName, group) in groups {
|
||||
if group.count > 1 {
|
||||
@@ -276,7 +585,7 @@ extension [TableAliasBase] {
|
||||
}
|
||||
}
|
||||
|
||||
var resolvedNames: [TableAliasBase: String] = [:]
|
||||
var resolvedNames: [TableAlias: String] = [:]
|
||||
for group in ambiguousGroups {
|
||||
var index = 1
|
||||
for alias in group {
|
||||
|
||||
@@ -138,7 +138,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
let region = try prefetchedRegion(
|
||||
db,
|
||||
associations: prefetchedAssociations,
|
||||
from: relation.source.tableName)
|
||||
from: relation.source.associationOriginTable ?? relation.source.tableName)
|
||||
statement.databaseRegion.formUnion(region)
|
||||
}
|
||||
|
||||
@@ -573,7 +573,7 @@ struct SQLQueryGenerator: Refinable {
|
||||
/// LIMIT ... -- limit
|
||||
private struct SQLQualifiedRelation: Sendable {
|
||||
/// All aliases, including aliases of joined relations
|
||||
var allAliases: [TableAliasBase] {
|
||||
var allAliases: [TableAlias] {
|
||||
joins.reduce(into: [source.alias].compactMap { $0 }) {
|
||||
$0.append(contentsOf: $1.value.relation.allAliases)
|
||||
}
|
||||
@@ -739,11 +739,17 @@ extension SQLQualifiedRelation: Refinable { }
|
||||
/// A "qualified" source, where all tables are identified with a table alias.
|
||||
private struct SQLQualifiedSource {
|
||||
var tableName: String
|
||||
var alias: TableAliasBase
|
||||
var alias: TableAlias
|
||||
|
||||
/// When not nil, use this table name instead of `tableName` when looking
|
||||
/// for foreign keys on this source. This string is not nil when an
|
||||
/// `SQLRelation` has been turned into a common table expression.
|
||||
var associationOriginTable: String?
|
||||
|
||||
init(_ source: SQLSource) {
|
||||
self.tableName = source.tableName
|
||||
self.alias = source.alias ?? TableAlias(tableName: source.tableName)
|
||||
self.associationOriginTable = source.associationOriginTable
|
||||
assert(alias.tableName == tableName)
|
||||
}
|
||||
|
||||
@@ -788,13 +794,13 @@ private struct SQLQualifiedJoin: Refinable {
|
||||
self.relation = SQLQualifiedRelation(child.relation)
|
||||
}
|
||||
|
||||
func sql(_ context: SQLGenerationContext, leftAlias: TableAliasBase) throws -> String {
|
||||
func sql(_ context: SQLGenerationContext, leftAlias: TableAlias) throws -> String {
|
||||
try sql(context, leftAlias: leftAlias, allowingInnerJoin: true)
|
||||
}
|
||||
|
||||
private func sql(
|
||||
_ context: SQLGenerationContext,
|
||||
leftAlias: TableAliasBase,
|
||||
leftAlias: TableAlias,
|
||||
allowingInnerJoin allowsInnerJoin: Bool)
|
||||
throws -> String
|
||||
{
|
||||
|
||||
@@ -1,443 +0,0 @@
|
||||
/// `TableAliasBase` is the base class of `TableAlias`.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#table-aliases> for more information and examples.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
public class TableAliasBase: @unchecked Sendable {
|
||||
// This Sendable conformance is transient. TableAlias IS NOT really Sendable.
|
||||
// TODO: Make TableAlias really Sendable
|
||||
private enum Impl {
|
||||
/// A TableAlias is undefined when it is created by the GRDB user:
|
||||
///
|
||||
/// let alias = TableAlias()
|
||||
/// let alias = TableAlias(name: "custom")
|
||||
case undefined(userName: String?)
|
||||
|
||||
/// A TableAlias is a table when explicitly specified:
|
||||
///
|
||||
/// let alias = TableAlias(tableName: "player")
|
||||
///
|
||||
/// Or when it qualifies a request that wasn't qualified yet (in which
|
||||
/// case it turns from undefined to a table):
|
||||
///
|
||||
/// // SELECT custom.* FROM player custom
|
||||
/// let alias = TableAlias(name: "custom")
|
||||
/// let request = Player.all().aliased(alias)
|
||||
case table(tableName: String, userName: String?)
|
||||
|
||||
/// A TableAlias can be a proxy for another table alias. Two different
|
||||
/// instances for the same table identifier:
|
||||
///
|
||||
/// // Pointless example: make alias2 a proxy for alias1
|
||||
/// let alias1 = TableAlias()
|
||||
/// let alias2 = TableAlias()
|
||||
/// Player.all()
|
||||
/// .aliased(alias1)
|
||||
/// .aliased(alias2)
|
||||
///
|
||||
/// Proxies are useful because queries get implicit aliases as soon
|
||||
/// as they are joined with associations. In the example below,
|
||||
/// customAlias becomes a proxy for the request's implicit alias, which
|
||||
/// gets a custom name. This allows implicit and user aliases to merge
|
||||
/// into a single "table identifier" that matches the user's expectations:
|
||||
///
|
||||
/// // SELECT custom.*, team.*
|
||||
/// // FROM player custom
|
||||
/// // JOIN team ON taem.id = custom.teamId
|
||||
/// // WHERE custom.name = 'Arthur'
|
||||
/// let customAlias = TableAlias(name: "custom")
|
||||
/// let request = Player
|
||||
/// .including(required: Player.team)
|
||||
/// .filter(sql: "custom.name = 'Arthur'")
|
||||
/// .aliased(customAlias)
|
||||
case proxy(TableAliasBase)
|
||||
}
|
||||
|
||||
private var impl: Impl
|
||||
|
||||
/// Resolve all proxies
|
||||
private var root: TableAliasBase {
|
||||
if case .proxy(let base) = impl {
|
||||
return base.root
|
||||
} else {
|
||||
return self
|
||||
}
|
||||
}
|
||||
|
||||
// exposed to SQLGenerationContext
|
||||
var identityName: String {
|
||||
userName ?? tableName
|
||||
}
|
||||
|
||||
// exposed to SQLGenerationContext
|
||||
var hasUserName: Bool {
|
||||
userName != nil
|
||||
}
|
||||
|
||||
var tableName: String {
|
||||
switch impl {
|
||||
case .undefined:
|
||||
// Likely a GRDB bug
|
||||
fatalError("Undefined alias has no table name")
|
||||
case .table(tableName: let tableName, userName: _):
|
||||
return tableName
|
||||
case .proxy(let base):
|
||||
return base.tableName
|
||||
}
|
||||
}
|
||||
|
||||
private var userName: String? {
|
||||
switch impl {
|
||||
case .undefined(let userName):
|
||||
return userName
|
||||
case .table(tableName: _, userName: let userName):
|
||||
return userName
|
||||
case .proxy(let base):
|
||||
return base.userName
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a TableAlias.
|
||||
///
|
||||
/// When the alias is given a name, this name is guaranteed to be used as
|
||||
/// the table alias in the SQL query:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT p.* FROM player p
|
||||
/// let alias = TableAlias(name: "p")
|
||||
/// let request = Player.all().aliased(alias)
|
||||
/// ```
|
||||
init(name: String? = nil) {
|
||||
self.impl = .undefined(userName: name)
|
||||
}
|
||||
|
||||
init(tableName: String, userName: String? = nil) {
|
||||
self.impl = .table(tableName: tableName, userName: userName)
|
||||
}
|
||||
|
||||
func becomeProxy(of base: TableAliasBase) {
|
||||
if self === base {
|
||||
return
|
||||
}
|
||||
|
||||
switch impl {
|
||||
case let .undefined(userName):
|
||||
if let userName {
|
||||
// rename
|
||||
assert(base.userName == nil || base.userName == userName)
|
||||
base.setUserName(userName)
|
||||
}
|
||||
self.impl = .proxy(base)
|
||||
case let .table(tableName: tableName, userName: userName):
|
||||
assert(tableName == base.tableName)
|
||||
if let userName {
|
||||
// rename
|
||||
assert(base.userName == nil || base.userName == userName)
|
||||
base.setUserName(userName)
|
||||
}
|
||||
self.impl = .proxy(base)
|
||||
case let .proxy(selfBase):
|
||||
selfBase.becomeProxy(of: base)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns nil if aliases can't be merged (conflict in tables, aliases...)
|
||||
func merged(with other: TableAliasBase) -> TableAliasBase? {
|
||||
if self === other {
|
||||
return self
|
||||
}
|
||||
|
||||
let root = self.root
|
||||
let otherRoot = other.root
|
||||
switch (root.impl, otherRoot.impl) {
|
||||
case let (.table(tableName: tableName, userName: userName),
|
||||
.table(tableName: otherTableName, userName: otherUserName)):
|
||||
guard tableName == otherTableName else {
|
||||
// can't merge
|
||||
return nil
|
||||
}
|
||||
if let userName, let otherUserName, userName != otherUserName {
|
||||
// can't merge
|
||||
return nil
|
||||
}
|
||||
root.becomeProxy(of: otherRoot)
|
||||
return otherRoot
|
||||
default:
|
||||
// can't merge
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
private func setUserName(_ userName: String) {
|
||||
switch impl {
|
||||
case .undefined:
|
||||
self.impl = .undefined(userName: userName)
|
||||
case .table(tableName: let tableName, userName: _):
|
||||
self.impl = .table(tableName: tableName, userName: userName)
|
||||
case .proxy(let base):
|
||||
base.setUserName(userName)
|
||||
}
|
||||
}
|
||||
|
||||
func setTableName(_ tableName: String) {
|
||||
switch impl {
|
||||
case .undefined(let userName):
|
||||
self.impl = .table(tableName: tableName, userName: userName)
|
||||
case .table(tableName: let initialTableName, userName: _):
|
||||
// It is a programmer error to reuse the same TableAlias for
|
||||
// multiple tables.
|
||||
//
|
||||
// // Don't do that
|
||||
// let alias = TableAlias()
|
||||
// let books = Book.aliased(alias)...
|
||||
// let authors = Author.aliased(alias)...
|
||||
GRDBPrecondition(
|
||||
tableName.lowercased() == initialTableName.lowercased(),
|
||||
"A TableAlias most not be used to refer to multiple tables")
|
||||
case .proxy(let base):
|
||||
base.setTableName(tableName)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension TableAliasBase: Equatable {
|
||||
public static func == (lhs: TableAliasBase, rhs: TableAliasBase) -> Bool {
|
||||
ObjectIdentifier(lhs.root) == ObjectIdentifier(rhs.root)
|
||||
}
|
||||
}
|
||||
|
||||
extension TableAliasBase: Hashable {
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(ObjectIdentifier(root))
|
||||
}
|
||||
}
|
||||
|
||||
extension TableAliasBase {
|
||||
/// Returns a result column that refers to the aliased table.
|
||||
public subscript(_ selectable: some SQLSelectable) -> SQLSelection {
|
||||
// TODO: test
|
||||
selectable.sqlSelection.qualified(with: self)
|
||||
}
|
||||
|
||||
/// Returns an SQL expression that refers to the aliased table.
|
||||
///
|
||||
/// For example, let's sort books by author name first, and then by title:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let title = Column("title")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT book.*
|
||||
/// // FROM book
|
||||
/// // JOIN author ON author.id = book.authorId
|
||||
/// // ORDER BY author.name, book.title
|
||||
/// let authorAlias = TableAlias<Author>()
|
||||
/// let request = Book
|
||||
/// .joining(required: Book.author.aliased(authorAlias))
|
||||
/// .order { [authorAlias.name, $0.title] }
|
||||
/// ```
|
||||
public subscript(_ expression: some SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> SQLExpression {
|
||||
expression.sqlExpression.qualified(with: self)
|
||||
}
|
||||
|
||||
public subscript(_ expression: some SQLJSONExpressible &
|
||||
SQLSpecificExpressible &
|
||||
SQLSelectable &
|
||||
SQLOrderingTerm)
|
||||
-> AnySQLJSONExpressible
|
||||
{
|
||||
AnySQLJSONExpressible(sqlExpression: expression.sqlExpression.qualified(with: self))
|
||||
}
|
||||
|
||||
public subscript(_ ordering: some SQLOrderingTerm) -> SQLOrdering {
|
||||
ordering.sqlOrdering.qualified(with: self)
|
||||
}
|
||||
|
||||
/// Returns an SQL column that refers to the aliased table.
|
||||
///
|
||||
/// For example, let's sort 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()
|
||||
/// let request = Book
|
||||
/// .joining(required: Book.author.aliased(authorAlias))
|
||||
/// .order(authorAlias["name"], Column("title"))
|
||||
/// ```
|
||||
public subscript(_ column: String) -> SQLExpression {
|
||||
.qualifiedColumn(column, self)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TableAlias
|
||||
|
||||
/// A TableAlias identifies a table in a request.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#table-aliases> for more information and examples.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
/// ## Topics
|
||||
///
|
||||
/// ## Supporting Types
|
||||
///
|
||||
/// - ``TableAliasBase``
|
||||
@dynamicMemberLookup
|
||||
public final class TableAlias<RowDecoder>: TableAliasBase, @unchecked Sendable {
|
||||
init(tableName: String, userName: String? = nil)
|
||||
where RowDecoder == Void
|
||||
{
|
||||
super.init(tableName: tableName, userName: userName)
|
||||
}
|
||||
|
||||
init(root: TableAliasBase) {
|
||||
super.init()
|
||||
becomeProxy(of: root)
|
||||
}
|
||||
|
||||
/// Creates an anonymous TableAlias.
|
||||
///
|
||||
/// When the alias is given a name, this name is guaranteed to be used as
|
||||
/// the table alias in the SQL query:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT p.* FROM player p
|
||||
/// let alias = TableAlias(name: "p")
|
||||
/// let request = Player.all().aliased(alias)
|
||||
/// ```
|
||||
///
|
||||
/// Anonymous aliases do not provide convenience access to table
|
||||
/// columns, unlike record aliases. See ``TableAlias`` for
|
||||
/// more information.
|
||||
public init(name: String? = nil)
|
||||
where RowDecoder == Void
|
||||
{
|
||||
super.init(name: name)
|
||||
}
|
||||
|
||||
/// Creates a TableAlias for the specified record type.
|
||||
///
|
||||
/// When the alias is given a name, this name is guaranteed to be used as
|
||||
/// the table alias in the SQL query:
|
||||
///
|
||||
/// ```swift
|
||||
/// // SELECT p.* FROM player p
|
||||
/// let alias = TableAlias<Player>(name: "p")
|
||||
/// let request = Player.all().aliased(alias)
|
||||
/// ```
|
||||
public init(
|
||||
name: String? = nil,
|
||||
for record: RowDecoder.Type = RowDecoder.self
|
||||
) {
|
||||
super.init(name: name)
|
||||
}
|
||||
}
|
||||
|
||||
extension TableAlias {
|
||||
/// A boolean SQL expression indicating whether this alias refers to some
|
||||
/// rows, or not.
|
||||
///
|
||||
/// In the example below, we only fetch books that are not associated to
|
||||
/// any author:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord, FetchableRecord { }
|
||||
/// struct Book: TableRecord, FetchableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let authorAlias = TableAlias<Author>()
|
||||
/// let request = Book
|
||||
/// .joining(optional: Book.author.aliased(authorAlias))
|
||||
/// .filter(!authorAlias.exists)
|
||||
/// let books = try request.fetchAll(db)
|
||||
/// }
|
||||
/// ```
|
||||
public var exists: SQLExpression {
|
||||
SQLExpression.qualifiedExists(self)
|
||||
}
|
||||
}
|
||||
|
||||
extension TableAlias where RowDecoder: TableRecord {
|
||||
public typealias DatabaseComponents = RowDecoder.DatabaseComponents
|
||||
|
||||
/// Returns a result column that refers to the aliased table.
|
||||
public subscript<T>(
|
||||
dynamicMember keyPath: KeyPath<DatabaseComponents, T>
|
||||
) -> SQLSelection
|
||||
where T: SQLSelectable
|
||||
{
|
||||
self[RowDecoder.databaseComponents[keyPath: keyPath]]
|
||||
}
|
||||
|
||||
/// Returns an SQL expression that refers to the aliased table.
|
||||
///
|
||||
/// For example, let's sort books by author name first, and then by title:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let title = Column("title")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT book.*
|
||||
/// // FROM book
|
||||
/// // JOIN author ON author.id = book.authorId
|
||||
/// // ORDER BY author.name, book.title
|
||||
/// let authorAlias = TableAlias<Author>()
|
||||
/// let request = Book
|
||||
/// .joining(required: Book.author.aliased(authorAlias))
|
||||
/// .order { [authorAlias.name, $0.title] }
|
||||
/// ```
|
||||
public subscript<T>(
|
||||
dynamicMember keyPath: KeyPath<DatabaseComponents, T>
|
||||
) -> SQLExpression
|
||||
where T: SQLSpecificExpressible &
|
||||
SQLSelectable &
|
||||
SQLOrderingTerm
|
||||
{
|
||||
self[RowDecoder.databaseComponents[keyPath: keyPath]]
|
||||
}
|
||||
|
||||
public subscript<T>(
|
||||
dynamicMember keyPath: KeyPath<DatabaseComponents, T>
|
||||
) -> AnySQLJSONExpressible
|
||||
where T: SQLJSONExpressible &
|
||||
SQLSpecificExpressible &
|
||||
SQLSelectable &
|
||||
SQLOrderingTerm
|
||||
{
|
||||
self[RowDecoder.databaseComponents[keyPath: keyPath]]
|
||||
}
|
||||
|
||||
public subscript<T>(
|
||||
dynamicMember keyPath: KeyPath<DatabaseComponents, T>
|
||||
) -> SQLOrdering
|
||||
where T: SQLOrderingTerm {
|
||||
self[RowDecoder.databaseComponents[keyPath: keyPath]]
|
||||
}
|
||||
}
|
||||
@@ -199,7 +199,7 @@ extension SQLInterpolation {
|
||||
|
||||
/// Appends the request SQL (not wrapped inside parentheses).
|
||||
///
|
||||
/// let subquery = Player.select { max($0.score) }
|
||||
/// let subquery = Player.select(max(Column("score")))
|
||||
/// // or
|
||||
/// let subQuery: SQLRequest<Int> = "SELECT MAX(score) FROM player"
|
||||
///
|
||||
|
||||
@@ -339,7 +339,7 @@ extension Database {
|
||||
/// // CREATE VIEW hero AS SELECT * FROM player WHERE isHero == 1
|
||||
/// try db.create(
|
||||
/// view: "hero",
|
||||
/// as: Player.filter(\.isHero))
|
||||
/// as: Player.filter(Column("isHero") == true))
|
||||
/// ```
|
||||
///
|
||||
/// When creating views in <doc:Migrations>, it is not recommended to
|
||||
|
||||
@@ -125,28 +125,6 @@ public final class TableAlteration {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Take care, when you rename **foreign keys** in <doc:Migrations>,
|
||||
/// to run the migration with the ``DatabaseMigrator/ForeignKeyChecks/immediate``
|
||||
/// foreign key checks, in order to avoid integrity failures:
|
||||
///
|
||||
/// ```swift
|
||||
/// // RECOMMENDED: rename foreign keys with immediate foreign key checks.
|
||||
/// migrator.registerMigration("Guilds", foreignKeyChecks: .immediate) { db in
|
||||
/// try db.rename(table: "team", to: "guild")
|
||||
/// try db.alter(table: "player") { t in
|
||||
/// t.rename(column: "teamId", to: "guildId")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // NOT RECOMMENDED: rename foreign keys with disabled foreign keys.
|
||||
/// migrator.registerMigration("Guilds") { db in
|
||||
/// try db.rename(table: "team", to: "guild")
|
||||
/// try db.alter(table: "player") { t in
|
||||
/// t.rename(column: "teamId", to: "guildId")
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Related SQLite documentation: <https://www.sqlite.org/lang_altertable.html>
|
||||
///
|
||||
/// - parameter name: the old name of the column.
|
||||
|
||||
@@ -308,31 +308,18 @@ extension TableRecord {
|
||||
/// latest message:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Chat: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let id = Column("id")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Message: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let date = Column("date")
|
||||
/// static let chatId = Column("chatId")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let latestMessageRequest = Message
|
||||
/// .annotated { max($0.date) }
|
||||
/// .group(\.chatId)
|
||||
/// .annotated(with: max(Column("date")))
|
||||
/// .group(Column("chatID"))
|
||||
///
|
||||
/// let latestMessageCTE = CommonTableExpression<Message>(
|
||||
/// let latestMessageCTE = CommonTableExpression(
|
||||
/// named: "latestMessage",
|
||||
/// request: latestMessageRequest)
|
||||
///
|
||||
/// let latestMessageAssociation = Chat.association(
|
||||
/// to: latestMessageCTE,
|
||||
/// on: { chat, latestMessage in
|
||||
/// chat.id == latestMessage.chatId
|
||||
/// chat[Column("id")] == latestMessage[Column("chatID")]
|
||||
/// })
|
||||
///
|
||||
/// // WITH latestMessage AS
|
||||
@@ -352,17 +339,12 @@ extension TableRecord {
|
||||
/// - returns: An association to the common table expression.
|
||||
public static func association<Destination>(
|
||||
to cte: CommonTableExpression<Destination>,
|
||||
on condition: @escaping @Sendable (
|
||||
_ left: TableAlias<Self>,
|
||||
_ right: TableAlias<Destination>
|
||||
) -> any SQLExpressible)
|
||||
on condition: @escaping @Sendable (_ left: TableAlias, _ right: TableAlias) -> any SQLExpressible)
|
||||
-> JoinAssociation<Self, Destination>
|
||||
{
|
||||
JoinAssociation(
|
||||
to: cte.relationForAll,
|
||||
condition: .expression { left, right in
|
||||
condition(TableAlias(root: left), TableAlias(root: right)).sqlExpression
|
||||
})
|
||||
condition: .expression { condition($0, $1).sqlExpression })
|
||||
}
|
||||
|
||||
/// Creates an association to a common table expression.
|
||||
@@ -718,17 +700,12 @@ extension TableRecord {
|
||||
/// For example, we can fetch only books whose author is French:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord, FetchableRecord, Decodable {
|
||||
/// enum Columns {
|
||||
/// static let countryCode = Column("countryCode")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Author: TableRecord, FetchableRecord, Decodable { }
|
||||
/// struct Book: TableRecord, FetchableRecord, Decodable {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
/// }
|
||||
///
|
||||
/// let frenchAuthors = Book.author.filter { $0.countryCode == "FR" }
|
||||
/// let frenchAuthors = Book.author.filter(Column("countryCode") == "FR")
|
||||
/// let bookInfos = try Book
|
||||
/// .joining(required: frenchAuthors)
|
||||
/// .fetchAll(db)
|
||||
@@ -749,19 +726,9 @@ extension TableRecord {
|
||||
/// 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 LEFT JOIN team ...
|
||||
/// let teamColor = Player.team.select(\.color)
|
||||
/// let teamColor = Player.team.select(Column("color"))
|
||||
/// let request = Player.annotated(withOptional: teamColor)
|
||||
/// ```
|
||||
///
|
||||
@@ -783,19 +750,9 @@ extension TableRecord {
|
||||
/// 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(\.color)
|
||||
/// let teamColor = Player.team.select(Column("color"))
|
||||
/// let request = Player.annotated(withRequired: teamColor)
|
||||
/// ```
|
||||
///
|
||||
|
||||
@@ -67,38 +67,6 @@ extension TableRecord {
|
||||
all().select(selection)
|
||||
}
|
||||
|
||||
/// Returns a request that selects the provided result columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord { }
|
||||
///
|
||||
/// // SELECT score FROM player
|
||||
/// let request = Player.select(\.score)
|
||||
/// ```
|
||||
public static func select(
|
||||
_ selection: (DatabaseComponents) throws -> any SQLSelectable
|
||||
) rethrows -> QueryInterfaceRequest<Self> {
|
||||
try all().select(selection)
|
||||
}
|
||||
|
||||
/// Returns a request that selects the provided result columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord { }
|
||||
///
|
||||
/// // SELECT id, score FROM player
|
||||
/// let request = Player.select { [$0.id, $0.score] }
|
||||
/// ```
|
||||
public static func select(
|
||||
_ selection: (DatabaseComponents) throws -> [any SQLSelectable]
|
||||
) rethrows -> QueryInterfaceRequest<Self> {
|
||||
try all().select(selection)
|
||||
}
|
||||
|
||||
/// Returns a request that selects the provided SQL string.
|
||||
///
|
||||
/// For example:
|
||||
@@ -195,35 +163,6 @@ extension TableRecord {
|
||||
all().select(selection, as: type)
|
||||
}
|
||||
|
||||
/// Returns a request that selects the provided 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.select(\.id, as: Int.self)
|
||||
/// let scores = try request.fetchSet(db) // Set<Int>
|
||||
///
|
||||
/// // SELECT MAX(score) FROM player
|
||||
/// let request = Player.select({ max($0.score) }, as: Int.self)
|
||||
/// let maxScore = try request.fetchOne(db) // Int?
|
||||
/// ```
|
||||
public static func select<RowDecoder>(
|
||||
_ selection: (DatabaseComponents) throws -> any SQLSelectable,
|
||||
as type: RowDecoder.Type = RowDecoder.self
|
||||
) rethrows -> QueryInterfaceRequest<RowDecoder>
|
||||
{
|
||||
try all().select(selection, as: type)
|
||||
}
|
||||
|
||||
/// Returns a request that selects the provided SQL string, and defines the
|
||||
/// type of decoded rows.
|
||||
///
|
||||
@@ -380,46 +319,6 @@ extension TableRecord {
|
||||
all().annotated(with: selection)
|
||||
}
|
||||
|
||||
/// Returns a request with the provided result columns appended to the
|
||||
/// record selection.
|
||||
///
|
||||
/// The record selection is determined by
|
||||
/// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord { }
|
||||
///
|
||||
/// // SELECT *, score + bonus AS totalScore FROM player
|
||||
/// let request = Player.annotated { ($0.score + $0.bonus).forKey("totalScore") }
|
||||
/// ```
|
||||
public static func annotated(
|
||||
with selection: (DatabaseComponents) throws -> any SQLSelectable
|
||||
) rethrows -> QueryInterfaceRequest<Self> {
|
||||
try all().annotated(with: selection)
|
||||
}
|
||||
|
||||
/// Returns a request with the provided result columns appended to the
|
||||
/// record selection.
|
||||
///
|
||||
/// The record selection is determined by
|
||||
/// ``TableRecord/databaseSelection-7iphs``, which defaults to all columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord { }
|
||||
///
|
||||
/// // SELECT *, score + bonus AS totalScore FROM player
|
||||
/// let request = Player.annotated { [($0.score + $0.bonus).forKey("totalScore")] }
|
||||
/// ```
|
||||
public static func annotated(
|
||||
with selection: (DatabaseComponents) throws -> [any SQLSelectable]
|
||||
) rethrows -> QueryInterfaceRequest<Self> {
|
||||
try all().annotated(with: selection)
|
||||
}
|
||||
|
||||
// Accept SQLSpecificExpressible instead of SQLExpressible, so that we
|
||||
// prevent the `Player.filter(42)` misuse.
|
||||
// See https://github.com/groue/GRDB.swift/pull/864
|
||||
@@ -438,26 +337,6 @@ extension TableRecord {
|
||||
all().filter(predicate)
|
||||
}
|
||||
|
||||
// Accept SQLSpecificExpressible instead of SQLExpressible, so that we
|
||||
// prevent the `Player.filter(42)` misuse.
|
||||
// See https://github.com/groue/GRDB.swift/pull/864
|
||||
/// Returns a request filtered with a boolean SQL expression.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord { }
|
||||
///
|
||||
/// // SELECT * FROM player WHERE name = 'O''Brien'
|
||||
/// let name = "O'Brien"
|
||||
/// let request = Player.filter { $0.name == name }
|
||||
/// ```
|
||||
public static func filter(
|
||||
_ predicate: (DatabaseComponents) throws -> any SQLSpecificExpressible
|
||||
) rethrows -> QueryInterfaceRequest<Self> {
|
||||
try all().filter(predicate)
|
||||
}
|
||||
|
||||
/// Returns a request filtered by primary key.
|
||||
///
|
||||
/// All single-column primary keys are supported:
|
||||
@@ -621,38 +500,6 @@ extension TableRecord {
|
||||
all().order(orderings)
|
||||
}
|
||||
|
||||
/// Returns a request sorted according to the given SQL ordering term.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord { }
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY score DESC
|
||||
/// let request = Player.order(\.score.desc)
|
||||
/// ```
|
||||
public static func order(
|
||||
_ orderings: (DatabaseComponents) throws -> any SQLOrderingTerm
|
||||
) rethrows -> QueryInterfaceRequest<Self> {
|
||||
try all().order(orderings)
|
||||
}
|
||||
|
||||
/// Returns a request sorted according to the given SQL ordering terms.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord { }
|
||||
///
|
||||
/// // SELECT * FROM player ORDER BY score DESC, name
|
||||
/// let request = Player.order { [$0.score.desc, $0.name] }
|
||||
/// ```
|
||||
public static func order(
|
||||
_ orderings: (DatabaseComponents) throws -> [any SQLOrderingTerm]
|
||||
) rethrows -> QueryInterfaceRequest<Self> {
|
||||
try all().order(orderings)
|
||||
}
|
||||
|
||||
/// Returns a request sorted by primary key.
|
||||
///
|
||||
/// All primary keys are supported:
|
||||
@@ -748,45 +595,8 @@ extension TableRecord {
|
||||
/// .joining(required: Book.author.filter(Column("deathDate") <= bookAlias[Column("publishDate")])
|
||||
/// ```
|
||||
///
|
||||
/// See ``TableRequest/aliased(_:)-772vb`` for more information.
|
||||
public static func aliased(_ alias: TableAlias<Void>) -> QueryInterfaceRequest<Self> {
|
||||
all().aliased(alias)
|
||||
}
|
||||
|
||||
/// Returns a request that can be referred to with the provided alias.
|
||||
///
|
||||
/// Use this method when you need to refer to this table from
|
||||
/// another request.
|
||||
///
|
||||
/// For example, the request below fetches posthumous books:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Author: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let deathDate = Column("deathDate")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Book: TableRecord {
|
||||
/// static let author = belongsTo(Author.self)
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let publishDate = Column("publishDate")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // SELECT book.*
|
||||
/// // FROM book
|
||||
/// // JOIN author ON author.id = book.authorId
|
||||
/// // AND author.deathDate <= book.publishDate
|
||||
/// let bookAlias = TableAlias<Book>()
|
||||
/// let request = Book
|
||||
/// .aliased(bookAlias)
|
||||
/// .joining(required: Book.author.filter { $0.deathDate <= bookAlias.publishDate })
|
||||
/// ```
|
||||
///
|
||||
/// See ``TableRequest/aliased(_:)-3k5h4`` for more information.
|
||||
public static func aliased(_ alias: TableAlias<Self>) -> QueryInterfaceRequest<Self> {
|
||||
/// See ``TableRequest/aliased(_:)`` for more information.
|
||||
public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest<Self> {
|
||||
all().aliased(alias)
|
||||
}
|
||||
|
||||
@@ -796,31 +606,18 @@ extension TableRecord {
|
||||
/// latest message:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Chat: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let id = Column("id")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// struct Message: TableRecord {
|
||||
/// enum Columns {
|
||||
/// static let date = Column("date")
|
||||
/// static let chatId = Column("chatId")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let latestMessageRequest = Message
|
||||
/// .annotated { max($0.date) }
|
||||
/// .group(\.chatId)
|
||||
/// .annotated(with: max(Column("date")))
|
||||
/// .group(Column("chatID"))
|
||||
///
|
||||
/// let latestMessageCTE = CommonTableExpression<Message>(
|
||||
/// let latestMessageCTE = CommonTableExpression(
|
||||
/// named: "latestMessage",
|
||||
/// request: latestMessageRequest)
|
||||
///
|
||||
/// let latestMessageAssociation = Chat.association(
|
||||
/// to: latestMessageCTE,
|
||||
/// on: { chat, latestMessage in
|
||||
/// chat.id == latestMessage.chatId
|
||||
/// chat[Column("id")] == latestMessage[Column("chatID")]
|
||||
/// })
|
||||
///
|
||||
/// // WITH latestMessage AS
|
||||
|
||||
@@ -39,7 +39,7 @@ import Foundation // For JSONEncoder
|
||||
/// - ``databaseChanges(from:)``
|
||||
/// - ``databaseChanges(modify:)``
|
||||
/// - ``databaseEquals(_:)``
|
||||
public protocol EncodableRecord: SendableMetatype {
|
||||
public protocol EncodableRecord {
|
||||
/// Encodes the record into the provided persistence container.
|
||||
///
|
||||
/// In your implementation of this method, store in the `container` argument
|
||||
|
||||
@@ -212,20 +212,20 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
|
||||
|
||||
// swiftlint:disable comma
|
||||
// swiftlint:disable line_length
|
||||
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forColumn: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
func decode(_ type: String.Type, forKey key: Key) throws -> String { try decoder.row.decode(forKey: decodeColumn(forKey: key)) }
|
||||
// swiftlint:enable line_length
|
||||
// swiftlint:enable comma
|
||||
|
||||
|
||||
@@ -26,16 +26,10 @@ import Foundation
|
||||
/// struct Player: FetchableRecord, TableRecord, Decodable {
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let name = Column("name")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// let players = try Player.fetchAll(db)
|
||||
/// let player = try Player.filter { $0.name == "O'Brien" }.fetchOne(db)
|
||||
/// let players = try Player.order(\.score).fetchAll(db)
|
||||
/// let players = try Player.order(Column("score")).fetchAll(db)
|
||||
/// ```
|
||||
///
|
||||
/// ## Topics
|
||||
@@ -558,32 +552,20 @@ extension FetchableRecord {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: FetchableRecord, TableRecord {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column(CodingKeys.id)
|
||||
/// static let name = Column(CodingKeys.name)
|
||||
/// static let score = Column(CodingKeys.score)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let name = "O'Reilly"
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter { $0.name == name }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// SELECT * FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let players = try Player.fetchCursor(db, request)
|
||||
/// while let player = try players.next() {
|
||||
/// print(player.score)
|
||||
/// print(player.name)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
@@ -610,27 +592,15 @@ extension FetchableRecord {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: FetchableRecord, TableRecord {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column(CodingKeys.id)
|
||||
/// static let name = Column(CodingKeys.name)
|
||||
/// static let score = Column(CodingKeys.score)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let name = "O'Reilly"
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter { $0.name == name }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// SELECT * FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let players = try Player.fetchAll(db, request)
|
||||
@@ -658,27 +628,15 @@ extension FetchableRecord {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: FetchableRecord, TableRecord {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column(CodingKeys.id)
|
||||
/// static let name = Column(CodingKeys.name)
|
||||
/// static let score = Column(CodingKeys.score)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let name = "O'Reilly"
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter { $0.name == name }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE name = \(name) LIMIT 1
|
||||
/// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1
|
||||
/// """
|
||||
///
|
||||
/// let player = try Player.fetchOne(db, request)
|
||||
@@ -709,27 +667,15 @@ extension FetchableRecord where Self: Hashable {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: FetchableRecord, TableRecord, Hashable {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column(CodingKeys.id)
|
||||
/// static let name = Column(CodingKeys.name)
|
||||
/// static let score = Column(CodingKeys.score)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let name = "O'Reilly"
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter { $0.name == name }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// SELECT * FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let players = try Player.fetchSet(db, request)
|
||||
@@ -765,27 +711,15 @@ extension FetchRequest where RowDecoder: FetchableRecord {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: FetchableRecord, TableRecord {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column(CodingKeys.id)
|
||||
/// static let name = Column(CodingKeys.name)
|
||||
/// static let score = Column(CodingKeys.score)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let name = "O'Reilly"
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter { $0.name == name }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// SELECT * FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let players = try request.fetchCursor(db)
|
||||
@@ -814,27 +748,15 @@ extension FetchRequest where RowDecoder: FetchableRecord {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: FetchableRecord, TableRecord {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column(CodingKeys.id)
|
||||
/// static let name = Column(CodingKeys.name)
|
||||
/// static let score = Column(CodingKeys.score)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let name = "O'Reilly"
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter { $0.name == name }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// SELECT * FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let players = try request.fetchAll(db)
|
||||
@@ -854,27 +776,15 @@ extension FetchRequest where RowDecoder: FetchableRecord {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: FetchableRecord, TableRecord {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column(CodingKeys.id)
|
||||
/// static let name = Column(CodingKeys.name)
|
||||
/// static let score = Column(CodingKeys.score)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let name = "O'Reilly"
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter { $0.name == name }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE name = \(name) LIMIT 1
|
||||
/// SELECT * FROM player WHERE lastName = \(lastName) LIMIT 1
|
||||
/// """
|
||||
///
|
||||
/// let player = try request.fetchOne(db)
|
||||
@@ -895,27 +805,15 @@ extension FetchRequest where RowDecoder: FetchableRecord & Hashable {
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: FetchableRecord, TableRecord, Hashable {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column(CodingKeys.id)
|
||||
/// static let name = Column(CodingKeys.name)
|
||||
/// static let score = Column(CodingKeys.score)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// try dbQueue.read { db in
|
||||
/// let name = "O'Reilly"
|
||||
/// let lastName = "O'Reilly"
|
||||
///
|
||||
/// // Query interface request
|
||||
/// let request = Player.filter { $0.name == name }
|
||||
/// let request = Player.filter(Column("lastName") == lastName)
|
||||
///
|
||||
/// // SQL request
|
||||
/// let request: SQLRequest<Player> = """
|
||||
/// SELECT * FROM player WHERE name = \(name)
|
||||
/// SELECT * FROM player WHERE lastName = \(lastName)
|
||||
/// """
|
||||
///
|
||||
/// let players = try request.fetchSet(db)
|
||||
|
||||
@@ -42,11 +42,8 @@ final class DAO<Record: MutablePersistableRecord> {
|
||||
func upsertStatement(
|
||||
_ db: Database,
|
||||
onConflict conflictTargetColumns: [String],
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Record>) -> [ColumnAssignment])?,
|
||||
updateCondition: ((
|
||||
_ existing: TableAlias<Record>,
|
||||
_ excluded: TableAlias<Record>
|
||||
) -> any SQLExpressible)? = nil,
|
||||
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?,
|
||||
updateCondition: ((_ existing: TableAlias, _ excluded: TableAlias) -> any SQLExpressible)? = nil,
|
||||
returning selection: [any SQLSelectable])
|
||||
throws -> Statement
|
||||
{
|
||||
@@ -76,7 +73,7 @@ final class DAO<Record: MutablePersistableRecord> {
|
||||
// that no information stored in the record is lost, unless explicitly
|
||||
// requested by the user.
|
||||
sql += " DO UPDATE SET "
|
||||
let excluded = TableAlias<Record>(name: "excluded")
|
||||
let excluded = TableAlias(name: "excluded")
|
||||
var assignments = assignments?(excluded) ?? []
|
||||
let lowercaseExcludedColumns = Set(primaryKey.columns.map { $0.lowercased() })
|
||||
.union(conflictTargetColumns.map { $0.lowercased() })
|
||||
@@ -122,7 +119,7 @@ final class DAO<Record: MutablePersistableRecord> {
|
||||
}
|
||||
|
||||
// WHERE
|
||||
let existing = TableAlias<Record>(name: databaseTableName)
|
||||
let existing = TableAlias(name: databaseTableName)
|
||||
if let condition = updateCondition?(existing, excluded) {
|
||||
let context = SQLGenerationContext(db)
|
||||
sql += try " WHERE " + condition.sqlExpression.sql(context)
|
||||
@@ -256,7 +253,7 @@ final class DAO<Record: MutablePersistableRecord> {
|
||||
// Make sure the selection is qualified with a table alias, so
|
||||
// that selectables such as `.allColumns(excluding:)` can query
|
||||
// the database about the database table.
|
||||
let alias = TableAliasBase(tableName: databaseTableName)
|
||||
let alias = TableAlias(tableName: databaseTableName)
|
||||
let context = SQLGenerationContext(db, aliases: [alias])
|
||||
var sql = sql
|
||||
var arguments = arguments
|
||||
|
||||
@@ -268,73 +268,6 @@ extension MutablePersistableRecord {
|
||||
didSave(PersistenceSuccess(success.inserted))
|
||||
return success.returned
|
||||
}
|
||||
|
||||
/// Executes an `INSERT RETURNING` statement, and returns the selected
|
||||
/// columns from the inserted row.
|
||||
///
|
||||
/// This method helps dealing with default column values and
|
||||
/// generated columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A table with an auto-incremented primary key and a default value
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute(sql: """
|
||||
/// CREATE TABLE player(
|
||||
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
/// name TEXT,
|
||||
/// score INTEGER DEFAULT 1000)
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// // A player with partial database information
|
||||
/// struct PartialPlayer: MutablePersistableRecord {
|
||||
/// static let databaseTableName = "player"
|
||||
/// var name: String
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Insert a partial player, get the inserted score
|
||||
/// try dbQueue.write { db in
|
||||
/// var partialPlayer = PartialPlayer(name: "Alice")
|
||||
///
|
||||
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
|
||||
/// let score = try partialPlayer.insertAndFetch(db) { statement in
|
||||
/// try Int.fetchOne(statement)
|
||||
/// } select: {
|
||||
/// [$0.score]
|
||||
/// }
|
||||
/// print(score) // The inserted score
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution. If
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// is used.
|
||||
/// - parameter fetch: A closure that executes its ``Statement`` argument.
|
||||
/// If the conflict policy is `IGNORE`, the statement may return no row.
|
||||
/// - parameter select: A closure that returns the returned columns
|
||||
/// (must not be empty).
|
||||
/// - returns: The result of the `fetch` function.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
/// - precondition: The result of `select` is not empty.
|
||||
@inlinable // allow specialization so that empty callbacks are removed
|
||||
public mutating func insertAndFetch<T>(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
fetch: (Statement) throws -> T,
|
||||
select: (DatabaseComponents) throws -> [any SQLSelectable]
|
||||
) throws -> T
|
||||
where Self: TableRecord
|
||||
{
|
||||
try insertAndFetch(db, onConflict: conflictResolution, selection: select(Self.databaseComponents), fetch: fetch)
|
||||
}
|
||||
#else
|
||||
/// Executes an `INSERT RETURNING` statement, and returns a new record built
|
||||
/// from the inserted row.
|
||||
@@ -516,78 +449,6 @@ extension MutablePersistableRecord {
|
||||
didSave(PersistenceSuccess(success.inserted))
|
||||
return success.returned
|
||||
}
|
||||
|
||||
/// Executes an `INSERT RETURNING` statement, and returns the selected
|
||||
/// columns from the inserted row.
|
||||
///
|
||||
/// This method helps dealing with default column values and
|
||||
/// generated columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A table with an auto-incremented primary key and a default value
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute(sql: """
|
||||
/// CREATE TABLE player(
|
||||
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
/// name TEXT,
|
||||
/// score INTEGER DEFAULT 1000)
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// // A player with partial database information
|
||||
/// struct PartialPlayer: MutablePersistableRecord {
|
||||
/// static let databaseTableName = "player"
|
||||
/// var name: String
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Insert a partial player, get the inserted score
|
||||
/// try dbQueue.write { db in
|
||||
/// var partialPlayer = PartialPlayer(name: "Alice")
|
||||
///
|
||||
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
|
||||
/// let score = try partialPlayer.insertAndFetch(db) { statement in
|
||||
/// try Int.fetchOne(statement)
|
||||
/// } select: {
|
||||
/// [$0.score]
|
||||
/// }
|
||||
/// print(score) // The inserted score
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution. If
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// is used.
|
||||
/// - parameter fetch: A closure that executes its ``Statement`` argument.
|
||||
/// If the conflict policy is `IGNORE`, the statement may return no row.
|
||||
/// - parameter select: A closure that returns the returned columns
|
||||
/// (must not be empty).
|
||||
/// - returns: The result of the `fetch` function.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
/// - precondition: The result of `select` is not empty.
|
||||
@inlinable // allow specialization so that empty callbacks are removed
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public mutating func insertAndFetch<T>(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
fetch: (Statement) throws -> T,
|
||||
select: (DatabaseComponents) throws -> [any SQLSelectable]
|
||||
) throws -> T
|
||||
where Self: TableRecord
|
||||
{
|
||||
try insertAndFetch(
|
||||
db,
|
||||
onConflict: conflictResolution,
|
||||
selection: select(Self.databaseComponents),
|
||||
fetch: fetch)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,6 @@ extension MutablePersistableRecord {
|
||||
didSave(saved)
|
||||
}
|
||||
|
||||
// TODO: Make it possible to build assignments from $0.columnName
|
||||
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
|
||||
/// returns the upserted record.
|
||||
///
|
||||
@@ -129,7 +128,7 @@ extension MutablePersistableRecord {
|
||||
public mutating func upsertAndFetch(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
|
||||
throws -> Self
|
||||
where Self: FetchableRecord
|
||||
{
|
||||
@@ -157,7 +156,7 @@ extension MutablePersistableRecord {
|
||||
_ db: Database,
|
||||
as returnedType: T.Type,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
|
||||
throws -> T
|
||||
{
|
||||
try willSave(db)
|
||||
@@ -307,7 +306,7 @@ extension MutablePersistableRecord {
|
||||
public mutating func upsertAndFetch(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
|
||||
throws -> Self
|
||||
where Self: FetchableRecord
|
||||
{
|
||||
@@ -336,7 +335,7 @@ extension MutablePersistableRecord {
|
||||
_ db: Database,
|
||||
as returnedType: T.Type,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
|
||||
throws -> T
|
||||
{
|
||||
try willSave(db)
|
||||
@@ -379,7 +378,7 @@ extension MutablePersistableRecord {
|
||||
mutating func upsertAndFetchWithCallbacks<T>(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String],
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
|
||||
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?,
|
||||
selection: [any SQLSelectable],
|
||||
decode: (Row) throws -> T)
|
||||
throws -> (InsertionSuccess, T)
|
||||
@@ -409,7 +408,7 @@ extension MutablePersistableRecord {
|
||||
func upsertAndFetchWithoutCallbacks<T>(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String],
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
|
||||
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?,
|
||||
selection: [any SQLSelectable],
|
||||
decode: (Row) throws -> T)
|
||||
throws -> (InsertionSuccess, T)
|
||||
|
||||
@@ -61,7 +61,6 @@
|
||||
/// - ``insertAndFetch(_:onConflict:)``
|
||||
/// - ``insertAndFetch(_:onConflict:as:)``
|
||||
/// - ``insertAndFetch(_:onConflict:selection:fetch:)``
|
||||
/// - ``insertAndFetch(_:onConflict:fetch:select:)``
|
||||
/// - ``upsertAndFetch(_:onConflict:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:as:onConflict:doUpdate:)``
|
||||
///
|
||||
|
||||
@@ -200,73 +200,6 @@ extension PersistableRecord {
|
||||
didSave(PersistenceSuccess(success.inserted))
|
||||
return success.returned
|
||||
}
|
||||
|
||||
/// Executes an `INSERT RETURNING` statement, and returns the selected
|
||||
/// columns from the inserted row.
|
||||
///
|
||||
/// This method helps dealing with default column values and
|
||||
/// generated columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A table with an auto-incremented primary key and a default value
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute(sql: """
|
||||
/// CREATE TABLE player(
|
||||
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
/// name TEXT,
|
||||
/// score INTEGER DEFAULT 1000)
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// // A player with partial database information
|
||||
/// struct PartialPlayer: PersistableRecord {
|
||||
/// static let databaseTableName = "player"
|
||||
/// var name: String
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Insert a partial player, get the inserted score
|
||||
/// try dbQueue.write { db in
|
||||
/// let partialPlayer = PartialPlayer(name: "Alice")
|
||||
///
|
||||
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
|
||||
/// let score = try partialPlayer.insertAndFetch(db) { statement in
|
||||
/// try Int.fetchOne(statement)
|
||||
/// } select: {
|
||||
/// [$0.score]
|
||||
/// }
|
||||
/// print(score) // The inserted score
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution. If
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// is used.
|
||||
/// - parameter fetch: A closure that executes its ``Statement`` argument.
|
||||
/// If the conflict policy is `IGNORE`, the statement may return no row.
|
||||
/// - parameter select: A closure that returns the returned columns
|
||||
/// (must not be empty).
|
||||
/// - returns: The result of the `fetch` function.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
/// - precondition: The result of `select` is not empty.
|
||||
@inlinable // allow specialization so that empty callbacks are removed
|
||||
public func insertAndFetch<T>(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
fetch: (Statement) throws -> T,
|
||||
select: (DatabaseComponents) throws -> [any SQLSelectable]
|
||||
) throws -> T
|
||||
where Self: TableRecord
|
||||
{
|
||||
try insertAndFetch(db, onConflict: conflictResolution, selection: select(Self.databaseComponents), fetch: fetch)
|
||||
}
|
||||
#else
|
||||
/// Executes an `INSERT RETURNING` statement, and returns a new record built
|
||||
/// from the inserted row.
|
||||
@@ -414,78 +347,6 @@ extension PersistableRecord {
|
||||
didSave(PersistenceSuccess(success.inserted))
|
||||
return success.returned
|
||||
}
|
||||
|
||||
/// Executes an `INSERT RETURNING` statement, and returns the selected
|
||||
/// columns from the inserted row.
|
||||
///
|
||||
/// This method helps dealing with default column values and
|
||||
/// generated columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// // A table with an auto-incremented primary key and a default value
|
||||
/// try dbQueue.write { db in
|
||||
/// try db.execute(sql: """
|
||||
/// CREATE TABLE player(
|
||||
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
/// name TEXT,
|
||||
/// score INTEGER DEFAULT 1000)
|
||||
/// """)
|
||||
/// }
|
||||
///
|
||||
/// // A player with partial database information
|
||||
/// struct PartialPlayer: PersistableRecord {
|
||||
/// static let databaseTableName = "player"
|
||||
/// var name: String
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Insert a partial player, get the inserted score
|
||||
/// try dbQueue.write { db in
|
||||
/// let partialPlayer = PartialPlayer(name: "Alice")
|
||||
///
|
||||
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
|
||||
/// let score = try partialPlayer.insertAndFetch(db) { statement in
|
||||
/// try Int.fetchOne(statement)
|
||||
/// } select: {
|
||||
/// [$0.score]
|
||||
/// }
|
||||
/// print(score) // The inserted score
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution. If
|
||||
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
|
||||
/// is used.
|
||||
/// - parameter fetch: A closure that executes its ``Statement`` argument.
|
||||
/// If the conflict policy is `IGNORE`, the statement may return no row.
|
||||
/// - parameter select: A closure that returns the returned columns
|
||||
/// (must not be empty).
|
||||
/// - returns: The result of the `fetch` function.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
|
||||
/// error thrown by the persistence callbacks defined by the record type.
|
||||
/// - precondition: The result of `select` is not empty.
|
||||
@inlinable // allow specialization so that empty callbacks are removed
|
||||
@available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) // SQLite 3.35.0+
|
||||
public func insertAndFetch<T>(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
fetch: (Statement) throws -> T,
|
||||
select: (DatabaseComponents) throws -> [any SQLSelectable]
|
||||
) throws -> T
|
||||
where Self: TableRecord
|
||||
{
|
||||
try insertAndFetch(
|
||||
db,
|
||||
onConflict: conflictResolution,
|
||||
selection: select(Self.databaseComponents),
|
||||
fetch: fetch)
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,6 @@ extension PersistableRecord {
|
||||
didSave(saved)
|
||||
}
|
||||
|
||||
// TODO: Make it possible to build assignments from $0.columnName
|
||||
/// Executes an `INSERT ON CONFLICT DO UPDATE RETURNING` statement, and
|
||||
/// returns the upserted record.
|
||||
///
|
||||
@@ -129,7 +128,7 @@ extension PersistableRecord {
|
||||
public func upsertAndFetch(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
|
||||
throws -> Self
|
||||
where Self: FetchableRecord
|
||||
{
|
||||
@@ -157,7 +156,7 @@ extension PersistableRecord {
|
||||
_ db: Database,
|
||||
as returnedType: T.Type,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
|
||||
throws -> T
|
||||
{
|
||||
try willSave(db)
|
||||
@@ -307,7 +306,7 @@ extension PersistableRecord {
|
||||
public func upsertAndFetch(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
|
||||
throws -> Self
|
||||
where Self: FetchableRecord
|
||||
{
|
||||
@@ -336,7 +335,7 @@ extension PersistableRecord {
|
||||
_ db: Database,
|
||||
as returnedType: T.Type,
|
||||
onConflict conflictTarget: [String] = [],
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])? = nil)
|
||||
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])? = nil)
|
||||
throws -> T
|
||||
{
|
||||
try willSave(db)
|
||||
@@ -379,7 +378,7 @@ extension PersistableRecord {
|
||||
func upsertAndFetchWithCallbacks<T>(
|
||||
_ db: Database,
|
||||
onConflict conflictTarget: [String],
|
||||
doUpdate assignments: ((_ excluded: TableAlias<Self>) -> [ColumnAssignment])?,
|
||||
doUpdate assignments: ((_ excluded: TableAlias) -> [ColumnAssignment])?,
|
||||
selection: [any SQLSelectable],
|
||||
decode: (Row) throws -> T)
|
||||
throws -> (InsertionSuccess, T)
|
||||
|
||||
@@ -23,7 +23,6 @@
|
||||
///
|
||||
/// - ``insertAndFetch(_:onConflict:as:)``
|
||||
/// - ``insertAndFetch(_:onConflict:selection:fetch:)``
|
||||
/// - ``insertAndFetch(_:onConflict:fetch:select:)``
|
||||
/// - ``upsertAndFetch(_:onConflict:doUpdate:)``
|
||||
/// - ``upsertAndFetch(_:as:onConflict:doUpdate:)``
|
||||
///
|
||||
|
||||
+15
-202
@@ -49,23 +49,23 @@ import Foundation
|
||||
///
|
||||
/// ### Updating Records
|
||||
///
|
||||
/// - ``updateAll(_:onConflict:assignment:)``
|
||||
/// - ``updateAll(_:onConflict:assignments:)``
|
||||
/// - ``updateAll(_:onConflict:_:)-7vv9x``
|
||||
/// - ``updateAll(_:onConflict:_:)-7atfw``
|
||||
///
|
||||
/// ### Building Query Interface Requests
|
||||
///
|
||||
/// `TableRecord` provide convenience access to most ``DerivableRequest`` and
|
||||
/// ``QueryInterfaceRequest`` methods as static methods on the type itself.
|
||||
///
|
||||
/// - ``aliased(_:)-sdcd``
|
||||
/// - ``aliased(_:)``
|
||||
/// - ``all()``
|
||||
/// - ``annotated(with:)-3zi1n``
|
||||
/// - ``annotated(with:)-4xoen``
|
||||
/// - ``annotated(with:)-8ce7u``
|
||||
/// - ``annotated(with:)-58am5``
|
||||
/// - ``annotated(with:)-12jwq``
|
||||
/// - ``annotated(with:)-79389``
|
||||
/// - ``annotated(withOptional:)``
|
||||
/// - ``annotated(withRequired:)``
|
||||
/// - ``filter(_:)-4xvdh``
|
||||
/// - ``filter(_:)``
|
||||
/// - ``filter(id:)``
|
||||
/// - ``filter(ids:)``
|
||||
/// - ``filter(key:)-9ey53``
|
||||
@@ -84,15 +84,16 @@ import Foundation
|
||||
/// - ``matching(_:)-22m4o``
|
||||
/// - ``matching(_:)-1t8ph``
|
||||
/// - ``none()``
|
||||
/// - ``order(_:)-4j3ej``
|
||||
/// - ``order(_:)-53dja``
|
||||
/// - ``order(_:)-9rc11``
|
||||
/// - ``order(_:)-2033k``
|
||||
/// - ``order(literal:)``
|
||||
/// - ``order(sql:arguments:)``
|
||||
/// - ``orderByPrimaryKey()``
|
||||
/// - ``request(for:)``
|
||||
/// - ``select(_:)-1bgd1``
|
||||
/// - ``select(_:)-8yqls``
|
||||
/// - ``select(_:as:)-7zz91``
|
||||
/// - ``select(_:)-1gvtj``
|
||||
/// - ``select(_:)-5oylt``
|
||||
/// - ``select(_:as:)-1puz3``
|
||||
/// - ``select(_:as:)-tjh0``
|
||||
/// - ``select(literal:)``
|
||||
/// - ``select(literal:as:)``
|
||||
/// - ``select(sql:arguments:)``
|
||||
@@ -100,9 +101,6 @@ import Foundation
|
||||
/// - ``selectID()``
|
||||
/// - ``selectPrimaryKey(as:)``
|
||||
/// - ``with(_:)``
|
||||
/// - ``databaseComponents``
|
||||
/// - ``Columns``
|
||||
/// - ``DatabaseComponents``
|
||||
///
|
||||
/// ### Defining Associations
|
||||
///
|
||||
@@ -116,87 +114,7 @@ import Foundation
|
||||
/// - ``hasOne(_:key:using:)-4g9tm``
|
||||
/// - ``hasOne(_:key:using:)-4v5xa``
|
||||
/// - ``hasOne(_:through:using:key:)``
|
||||
///
|
||||
/// ### Legacy APIs
|
||||
///
|
||||
/// It is recommended to prefer the closure-based apis defined above, as
|
||||
/// well as record aliases over anonymous aliases.
|
||||
///
|
||||
/// - ``aliased(_:)-py77``
|
||||
/// - ``annotated(with:)-3zi1n``
|
||||
/// - ``annotated(with:)-79389``
|
||||
/// - ``filter(_:)-5u85w``
|
||||
/// - ``order(_:)-9rc11``
|
||||
/// - ``order(_:)-2033k``
|
||||
/// - ``select(_:)-1gvtj``
|
||||
/// - ``select(_:)-5oylt``
|
||||
/// - ``select(_:as:)-1puz3``
|
||||
/// - ``select(_:as:)-tjh0``
|
||||
/// - ``updateAll(_:onConflict:_:)-7vv9x``
|
||||
/// - ``updateAll(_:onConflict:_:)-7atfw``
|
||||
public protocol TableRecord: SendableMetatype {
|
||||
/// A type that defines columns.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column("id")
|
||||
/// static let name = Column("name")
|
||||
/// static let score = Column("score")
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// `Codable` types can define their columns from their coding keys:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord, Codable {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column(CodingKeys.id)
|
||||
/// static let name = Column(CodingKeys.name)
|
||||
/// static let score = Column(CodingKeys.score)
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
associatedtype Columns = Never
|
||||
|
||||
/// A type that provides database components to the query interface.
|
||||
///
|
||||
/// By default, it is `Columns.Type`. This default definition might
|
||||
/// change in future GRDB versions.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord, Codable {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column(CodingKeys.id)
|
||||
/// static let name = Column(CodingKeys.name)
|
||||
/// static let score = Column(CodingKeys.score)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// Player.DatabaseComponents // Player.Columns.Type by default
|
||||
/// Player.databaseComponents // Instance of Player.DatabaseComponents
|
||||
/// Player.databaseComponents.score // A Column
|
||||
/// let request = Player.order(\.score.desc)
|
||||
/// ```
|
||||
associatedtype DatabaseComponents = Columns.Type
|
||||
|
||||
public protocol TableRecord {
|
||||
/// The name of the database table used to build SQL queries.
|
||||
///
|
||||
/// For example:
|
||||
@@ -226,12 +144,7 @@ public protocol TableRecord: SendableMetatype {
|
||||
/// struct PartialPlayer: TableRecord {
|
||||
/// static let databaseTableName = "player"
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// [Columns.id, Columns.name]
|
||||
/// }
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column("id")
|
||||
/// static let name = Column("name")
|
||||
/// [Column("id"), Column("name")]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
@@ -269,31 +182,6 @@ public protocol TableRecord: SendableMetatype {
|
||||
/// > static let databaseSelection: [any SQLSelectable] = [.allColumns]
|
||||
/// > ```
|
||||
static var databaseSelection: [any SQLSelectable] { get }
|
||||
|
||||
/// The value that provides database components to the query interface.
|
||||
///
|
||||
/// By default, it is `Columns.self`. This default definition might
|
||||
/// change in future GRDB versions.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```swift
|
||||
/// struct Player: TableRecord, Codable {
|
||||
/// var id: Int64
|
||||
/// var name: String
|
||||
/// var score: Int
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column(CodingKeys.id)
|
||||
/// static let name = Column(CodingKeys.name)
|
||||
/// static let score = Column(CodingKeys.score)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// Player.databaseComponents.score // A Column
|
||||
/// let request = Player.order(\.score.desc)
|
||||
/// ```
|
||||
static var databaseComponents: DatabaseComponents { get }
|
||||
}
|
||||
|
||||
extension TableRecord {
|
||||
@@ -344,12 +232,6 @@ extension TableRecord {
|
||||
}
|
||||
}
|
||||
|
||||
extension TableRecord where DatabaseComponents == Columns.Type {
|
||||
public static var databaseComponents: DatabaseComponents {
|
||||
Columns.self
|
||||
}
|
||||
}
|
||||
|
||||
extension TableRecord {
|
||||
|
||||
// MARK: - Counting All
|
||||
@@ -387,12 +269,7 @@ extension TableRecord {
|
||||
/// struct PartialPlayer: TableRecord {
|
||||
/// static let databaseTableName = "player"
|
||||
/// static var databaseSelection: [any SQLSelectable] {
|
||||
/// [Columns.id, Columns.name]
|
||||
/// }
|
||||
///
|
||||
/// enum Columns {
|
||||
/// static let id = Column("id")
|
||||
/// static let name = Column("name")
|
||||
/// [Column("id"), Column("name")]
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
@@ -755,70 +632,6 @@ extension TableRecord {
|
||||
// MARK: - Batch Update
|
||||
|
||||
extension TableRecord {
|
||||
/// Updates all records, and returns the number of updated records.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```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) { $0.score.set(to: 0) }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution,
|
||||
/// defaulting to the record's persistenceConflictPolicy.
|
||||
/// - parameter assignments: A closure that returns an array of
|
||||
/// column assignments.
|
||||
/// - returns: The number of updated records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public static func updateAll(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
assignments: (DatabaseComponents) throws -> [ColumnAssignment]
|
||||
) throws -> Int {
|
||||
try updateAll(db, onConflict: conflictResolution, assignments(databaseComponents))
|
||||
}
|
||||
|
||||
/// Updates all records, and returns the number of updated records.
|
||||
///
|
||||
/// For example:
|
||||
///
|
||||
/// ```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) { $0.score.set(to: 0) }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - parameter db: A database connection.
|
||||
/// - parameter conflictResolution: A policy for conflict resolution,
|
||||
/// defaulting to the record's persistenceConflictPolicy.
|
||||
/// - parameter assignment: A closure that returns an assignment.
|
||||
/// - returns: The number of updated records.
|
||||
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
|
||||
@discardableResult
|
||||
public static func updateAll(
|
||||
_ db: Database,
|
||||
onConflict conflictResolution: Database.ConflictResolution? = nil,
|
||||
assignment: (DatabaseComponents) throws -> ColumnAssignment
|
||||
) throws -> Int {
|
||||
try updateAll(db, onConflict: conflictResolution, [assignment(databaseComponents)])
|
||||
}
|
||||
|
||||
/// Updates all records, and returns the number of updated records.
|
||||
///
|
||||
|
||||
@@ -27,7 +27,7 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
|
||||
self.attemptToFulfill = attemptToFulfill
|
||||
}
|
||||
|
||||
func receive<S>(subscriber: S) where S: Subscriber & SendableMetatype, Failure == S.Failure, Output == S.Input {
|
||||
func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = OnDemandFutureSubscription(
|
||||
attemptToFulfill: attemptToFulfill,
|
||||
downstream: subscriber)
|
||||
@@ -35,7 +35,7 @@ struct OnDemandFuture<Output, Failure: Error>: Publisher {
|
||||
}
|
||||
}
|
||||
|
||||
private class OnDemandFutureSubscription<Downstream: Subscriber & SendableMetatype>: Subscription, @unchecked Sendable {
|
||||
private class OnDemandFutureSubscription<Downstream: Subscriber>: Subscription, @unchecked Sendable {
|
||||
// @unchecked because `state` is protected with `lock`.
|
||||
typealias Promise = @Sendable (Result<Downstream.Input, Downstream.Failure>) -> Void
|
||||
|
||||
|
||||
@@ -63,9 +63,7 @@ final class Pool<T: Sendable>: Sendable {
|
||||
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
|
||||
private let itemsGroup: DispatchGroup // knows when no element is used
|
||||
private let barrierQueue: DispatchQueue
|
||||
private let barrierActor: DispatchQueueActor
|
||||
private let semaphoreWaitingQueue: DispatchQueue // Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
|
||||
private let semaphoreWaitingActor: DispatchQueueActor
|
||||
|
||||
/// Creates a Pool.
|
||||
///
|
||||
@@ -85,9 +83,7 @@ final class Pool<T: Sendable>: Sendable {
|
||||
self.itemsSemaphore = DispatchSemaphore(value: maximumCount)
|
||||
self.itemsGroup = DispatchGroup()
|
||||
self.barrierQueue = DispatchQueue(label: "GRDB.Pool.barrier", qos: qos, attributes: [.concurrent])
|
||||
self.barrierActor = DispatchQueueActor(queue: barrierQueue, flags: [.barrier])
|
||||
self.semaphoreWaitingQueue = DispatchQueue(label: "GRDB.Pool.wait", qos: qos)
|
||||
self.semaphoreWaitingActor = DispatchQueueActor(queue: semaphoreWaitingQueue)
|
||||
}
|
||||
|
||||
/// Returns a tuple (element, release)
|
||||
@@ -118,15 +114,6 @@ final class Pool<T: Sendable>: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a tuple (element, release)
|
||||
/// Client must call release(), only once, after the element has been used.
|
||||
func get() async throws -> ElementAndRelease {
|
||||
// See asyncGet(_:)
|
||||
try await semaphoreWaitingActor.execute {
|
||||
try self.get()
|
||||
}
|
||||
}
|
||||
|
||||
/// Eventually produces a tuple (element, release), where element is
|
||||
/// intended to be used asynchronously.
|
||||
///
|
||||
@@ -154,14 +141,6 @@ final class Pool<T: Sendable>: Sendable {
|
||||
return try block(element)
|
||||
}
|
||||
|
||||
/// Performs an asynchronous block with an element. The element turns
|
||||
/// available after the block has executed.
|
||||
func get<U>(block: (T) async throws -> U) async throws -> U {
|
||||
let (element, completion) = try await get()
|
||||
defer { completion(.reuse) }
|
||||
return try await block(element)
|
||||
}
|
||||
|
||||
private func release(_ item: Item, completion: PoolCompletion) {
|
||||
contentLock.withLock { content in
|
||||
switch completion {
|
||||
@@ -205,15 +184,6 @@ final class Pool<T: Sendable>: Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
func barrier<R: Sendable>(
|
||||
execute barrier: sending () throws -> sending R
|
||||
) async rethrows -> sending R {
|
||||
try await barrierActor.execute {
|
||||
itemsGroup.wait()
|
||||
return try barrier()
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously runs the `barrier` function when no element is used, and
|
||||
/// before any other element is dequeued.
|
||||
func asyncBarrier(execute barrier: @escaping @Sendable () -> Void) {
|
||||
|
||||
@@ -58,7 +58,7 @@ public protocol _ValueReducerFetcher: Sendable {
|
||||
/// ### Supporting Types
|
||||
///
|
||||
/// - ``ValueReducers``
|
||||
public protocol ValueReducer: _ValueReducer, SendableMetatype { }
|
||||
public protocol ValueReducer: _ValueReducer { }
|
||||
|
||||
/// A namespace for concrete types that adopt the ``ValueReducer`` protocol.
|
||||
public enum ValueReducers { }
|
||||
@@ -511,7 +511,7 @@ extension DatabasePublishers {
|
||||
self.start = start
|
||||
}
|
||||
|
||||
public func receive<S>(subscriber: S) where S: Subscriber & SendableMetatype, Failure == S.Failure, Output == S.Input {
|
||||
public func receive<S>(subscriber: S) where S: Subscriber, Failure == S.Failure, Output == S.Input {
|
||||
let subscription = ValueSubscription(
|
||||
start: start,
|
||||
downstream: subscriber)
|
||||
@@ -521,7 +521,7 @@ extension DatabasePublishers {
|
||||
|
||||
private class ValueSubscription<Downstream>:
|
||||
Subscription, @unchecked Sendable
|
||||
where Downstream: Subscriber & SendableMetatype,
|
||||
where Downstream: Subscriber,
|
||||
Downstream.Failure == Error
|
||||
{
|
||||
// @unchecked Sendable because `cancellable` and `state` are
|
||||
@@ -820,7 +820,7 @@ extension ValueObservation {
|
||||
///
|
||||
/// // Tracks the 'score' column in the 'player' table
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// region: Player.select(\.score),
|
||||
/// region: Player.select(Column("score"),
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks the 'score' column in the 'player' table
|
||||
@@ -892,7 +892,7 @@ extension ValueObservation {
|
||||
///
|
||||
/// // Tracks the 'score' column in the 'player' table
|
||||
/// let observation = ValueObservation.tracking(
|
||||
/// regions: [Player.select(\.score)],
|
||||
/// regions: [Player.select(Column("score")],
|
||||
/// fetch: { db in ... })
|
||||
///
|
||||
/// // Tracks the 'score' column in the 'player' table
|
||||
@@ -963,7 +963,7 @@ extension ValueObservation {
|
||||
/// let totalPlayerCount = try Player.fetchCount(db)
|
||||
///
|
||||
/// let bestPlayers = try Player
|
||||
/// .order(\.score.desc)
|
||||
/// .order(Column("score").desc)
|
||||
/// .limit(10)
|
||||
/// .fetchAll(db)
|
||||
///
|
||||
|
||||
@@ -47,7 +47,6 @@
|
||||
562205FE1E420EA2005860AC /* DatabasePoolConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 560A37AA1C90085D00949E71 /* DatabasePoolConcurrencyTests.swift */; };
|
||||
562205FF1E420EA2005860AC /* DatabasePoolReadOnlyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */; };
|
||||
562206091E420EB2005860AC /* DatabaseQueueConcurrencyTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 563363BC1C93FD5E000BE133 /* DatabaseQueueConcurrencyTests.swift */; };
|
||||
56231A462DCF3A28007676E4 /* TableAlias.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231A452DCF3A28007676E4 /* TableAlias.swift */; };
|
||||
56231E6325CEBF08001DFD2F /* RowDecodingError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56231E6025CEBF06001DFD2F /* RowDecodingError.swift */; };
|
||||
5623931B1DECC02000A6B01F /* RowFetchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 562393171DECC02000A6B01F /* RowFetchTests.swift */; };
|
||||
562393331DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */; };
|
||||
@@ -262,7 +261,6 @@
|
||||
56A8C2321D1914540096E9D4 /* UUID.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C22F1D1914540096E9D4 /* UUID.swift */; };
|
||||
56A8C2451D1918EF0096E9D4 /* FoundationNSUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C2361D1914790096E9D4 /* FoundationNSUUIDTests.swift */; };
|
||||
56A8C2461D1918EF0096E9D4 /* FoundationUUIDTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A8C21E1D1914110096E9D4 /* FoundationUUIDTests.swift */; };
|
||||
56AC93E12E291C9700DB6C74 /* DispatchQueueActor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AC93E02E291C9700DB6C74 /* DispatchQueueActor.swift */; };
|
||||
56AE6428222AACE300AD1B0B /* AssociationHasOneThroughSQLTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE6426222AACE300AD1B0B /* AssociationHasOneThroughSQLTests.swift */; };
|
||||
56AF746E1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AF746A1D41FB9C005E9FF3 /* DatabaseValueConvertibleEscapingTests.swift */; };
|
||||
56AFEF3229969F7E00CA1E51 /* TransactionClock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AFEF3029969F7E00CA1E51 /* TransactionClock.swift */; };
|
||||
@@ -502,7 +500,6 @@
|
||||
561F38DA2AC8914D0051EEE9 /* JSONColumnTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = JSONColumnTests.swift; sourceTree = "<group>"; };
|
||||
561F38F02AC9CE220051EEE9 /* DatabaseDataEncodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataEncodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
561F38F52AC9CE5A0051EEE9 /* DatabaseDataDecodingStrategyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseDataDecodingStrategyTests.swift; sourceTree = "<group>"; };
|
||||
56231A452DCF3A28007676E4 /* TableAlias.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableAlias.swift; sourceTree = "<group>"; };
|
||||
56231E6025CEBF06001DFD2F /* RowDecodingError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RowDecodingError.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>"; };
|
||||
@@ -782,7 +779,6 @@
|
||||
56A8C21E1D1914110096E9D4 /* FoundationUUIDTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationUUIDTests.swift; sourceTree = "<group>"; };
|
||||
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>"; };
|
||||
56AC93E02E291C9700DB6C74 /* DispatchQueueActor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DispatchQueueActor.swift; sourceTree = "<group>"; };
|
||||
56AE6426222AACE300AD1B0B /* 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>"; };
|
||||
56AFEF3029969F7E00CA1E51 /* TransactionClock.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TransactionClock.swift; sourceTree = "<group>"; };
|
||||
@@ -1279,7 +1275,6 @@
|
||||
5656A82A2295BD56001FF3FF /* SQLQueryGenerator.swift */,
|
||||
56F89E182A585E0D002FE2AA /* SQLTableAlterationGenerator.swift */,
|
||||
56F89E192A585E0D002FE2AA /* SQLTableGenerator.swift */,
|
||||
56231A452DCF3A28007676E4 /* TableAlias.swift */,
|
||||
);
|
||||
path = SQLGeneration;
|
||||
sourceTree = "<group>";
|
||||
@@ -1602,13 +1597,13 @@
|
||||
56A238751B9C75030082EB20 /* DatabaseValue.swift */,
|
||||
560D923E1C672C3E00F4F92B /* DatabaseValueConvertible.swift */,
|
||||
563363C31C942C37000BE133 /* DatabaseWriter.swift */,
|
||||
56AC93E02E291C9700DB6C74 /* DispatchQueueActor.swift */,
|
||||
5636E9BB1D22574100B9B05F /* FetchRequest.swift */,
|
||||
56A238761B9C75030082EB20 /* Row.swift */,
|
||||
567404871CEF84C8003ED5CC /* RowAdapter.swift */,
|
||||
56231E6025CEBF06001DFD2F /* RowDecodingError.swift */,
|
||||
56BB6EA81D3009B100A1CA52 /* SchedulingWatchdog.swift */,
|
||||
560A37A61C8FF6E500949E71 /* SerializedDatabase.swift */,
|
||||
56D3332129C38D7A00430680 /* WALSnapshotTransaction.swift */,
|
||||
56A6EB2226076F6A00C27594 /* SQL.swift */,
|
||||
56E9FAC32210468500C703A8 /* SQLInterpolation.swift */,
|
||||
56FBFED52210731000945324 /* SQLRequest.swift */,
|
||||
@@ -1618,7 +1613,6 @@
|
||||
56AFEF3029969F7E00CA1E51 /* TransactionClock.swift */,
|
||||
566B91321FA4D3810012D5B0 /* TransactionObserver.swift */,
|
||||
56564F3828637C9900A19E9F /* WALSnapshot.swift */,
|
||||
56D3332129C38D7A00430680 /* WALSnapshotTransaction.swift */,
|
||||
5605F1471C672E4000235C62 /* Support */,
|
||||
);
|
||||
path = Core;
|
||||
@@ -1995,7 +1989,6 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
5656A8712295BD56001FF3FF /* HasOneThroughAssociation.swift in Sources */,
|
||||
56231A462DCF3A28007676E4 /* TableAlias.swift in Sources */,
|
||||
56713FE32691F487006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
5685C1962AD52EF200DA4B7A /* ListDumpFormat.swift in Sources */,
|
||||
566BD7332927AFD600595649 /* ValueConcurrentObserver.swift in Sources */,
|
||||
@@ -2012,7 +2005,6 @@
|
||||
566B910B1FA4C3970012D5B0 /* Database+Statements.swift in Sources */,
|
||||
5656A8672295BD56001FF3FF /* HasOneAssociation.swift in Sources */,
|
||||
566B91251FA4CF810012D5B0 /* Database+Schema.swift in Sources */,
|
||||
56AC93E12E291C9700DB6C74 /* DispatchQueueActor.swift in Sources */,
|
||||
5656A85F2295BD56001FF3FF /* FTS3+QueryInterface.swift in Sources */,
|
||||
56012B82257404A400B4925B /* CommonTableExpression.swift in Sources */,
|
||||
5656A8972295BD56001FF3FF /* SQLRelation.swift in Sources */,
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>7.6.1</string>
|
||||
<string>7.3.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -7,10 +7,6 @@ private struct Team: Codable, FetchableRecord, PersistableRecord {
|
||||
static let customPlayers = hasMany(Player.self, key: "customPlayers")
|
||||
var id: Int64
|
||||
var name: String
|
||||
|
||||
enum Columns {
|
||||
static let name = Column(CodingKeys.name)
|
||||
}
|
||||
}
|
||||
|
||||
private struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
@@ -19,11 +15,6 @@ private struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
var teamId: Int64?
|
||||
var name: String
|
||||
var score: Int
|
||||
|
||||
enum Columns {
|
||||
static let name = Column(CodingKeys.name)
|
||||
static let score = Column(CodingKeys.score)
|
||||
}
|
||||
}
|
||||
|
||||
private struct Award: Codable, FetchableRecord, PersistableRecord {
|
||||
@@ -109,9 +100,9 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.select { $0.name }
|
||||
.select(Column("name"))
|
||||
.annotated(with: Team.players.count)
|
||||
.group { $0.name }
|
||||
.group(Column("name"))
|
||||
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "team"."name", COUNT(DISTINCT "player"."id") AS "playerCount" \
|
||||
@@ -121,31 +112,12 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=6.1)
|
||||
func testAggregateWithGroup_swift61() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.select(\.name)
|
||||
.annotated(with: Team.players.count)
|
||||
.group(\.name)
|
||||
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "team"."name", COUNT(DISTINCT "player"."id") AS "playerCount" \
|
||||
FROM "team" \
|
||||
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
|
||||
GROUP BY "team"."name"
|
||||
""")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
func testAnnotatedWithHasManyDefaultAverage() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.players.average { $0.score })
|
||||
.annotated(with: Team.players.average(Column("score")))
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: TeamInfo.self)
|
||||
|
||||
@@ -263,7 +235,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.players.max { $0.score })
|
||||
.annotated(with: Team.players.max(Column("score")))
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: TeamInfo.self)
|
||||
|
||||
@@ -296,45 +268,6 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=6.1)
|
||||
func testAnnotatedWithHasManyDefaultMax_Swift61() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.players.max(\.score))
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: TeamInfo.self)
|
||||
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "team".*, MAX("player"."score") AS "maxPlayerScore" \
|
||||
FROM "team" \
|
||||
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
|
||||
GROUP BY "team"."id" \
|
||||
ORDER BY "team"."id"
|
||||
""")
|
||||
|
||||
let teamInfos = try request.fetchAll(db)
|
||||
XCTAssertEqual(teamInfos.count, 4)
|
||||
|
||||
XCTAssertEqual(teamInfos[0].team.id, 1)
|
||||
XCTAssertEqual(teamInfos[0].team.name, "Reds")
|
||||
XCTAssertEqual(teamInfos[0].maxPlayerScore, 1000)
|
||||
|
||||
XCTAssertEqual(teamInfos[1].team.id, 2)
|
||||
XCTAssertEqual(teamInfos[1].team.name, "Blues")
|
||||
XCTAssertEqual(teamInfos[1].maxPlayerScore, 800)
|
||||
|
||||
XCTAssertEqual(teamInfos[2].team.id, 3)
|
||||
XCTAssertEqual(teamInfos[2].team.name, "Greens")
|
||||
XCTAssertNil(teamInfos[2].maxPlayerScore)
|
||||
|
||||
XCTAssertEqual(teamInfos[3].team.id, 4)
|
||||
XCTAssertEqual(teamInfos[3].team.name, "Oranges")
|
||||
XCTAssertEqual(teamInfos[3].maxPlayerScore, 0)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func testAnnotatedWithHasManyDefaultMaxJoiningRequired() throws {
|
||||
// It is important to have an explicit test for this technique because
|
||||
// it is the only currently available that forces a JOIN, and we don't
|
||||
@@ -344,7 +277,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.players.max { $0.score })
|
||||
.annotated(with: Team.players.max(Column("score")))
|
||||
.joining(required: Team.players) // <- the tested technique
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: TeamInfo.self)
|
||||
@@ -379,7 +312,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.players.min { $0.score })
|
||||
.annotated(with: Team.players.min(Column("score")))
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: TeamInfo.self)
|
||||
|
||||
@@ -416,7 +349,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.players.sum { $0.score })
|
||||
.annotated(with: Team.players.sum(Column("score")))
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: TeamInfo.self)
|
||||
|
||||
@@ -453,7 +386,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.players.total { $0.score })
|
||||
.annotated(with: Team.players.total(Column("score")))
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: TeamInfo.self)
|
||||
|
||||
@@ -490,10 +423,10 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.players.average { $0.score })
|
||||
.annotated(with: Team.players.average(Column("score")))
|
||||
.annotated(with: Team.players.count)
|
||||
.annotated(with: Team.players.min { $0.score }, Team.players.max { $0.score })
|
||||
.annotated(with: Team.players.sum { $0.score })
|
||||
.annotated(with: Team.players.min(Column("score")), Team.players.max(Column("score")))
|
||||
.annotated(with: Team.players.sum(Column("score")))
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: TeamInfo.self)
|
||||
|
||||
@@ -551,7 +484,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.customPlayers.average { $0.score })
|
||||
.annotated(with: Team.customPlayers.average(Column("score")))
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: CustomTeamInfo.self)
|
||||
|
||||
@@ -625,7 +558,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.customPlayers.max { $0.score })
|
||||
.annotated(with: Team.customPlayers.max(Column("score")))
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: CustomTeamInfo.self)
|
||||
|
||||
@@ -662,7 +595,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.customPlayers.min { $0.score })
|
||||
.annotated(with: Team.customPlayers.min(Column("score")))
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: CustomTeamInfo.self)
|
||||
|
||||
@@ -699,7 +632,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.customPlayers.sum { $0.score })
|
||||
.annotated(with: Team.customPlayers.sum(Column("score")))
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: CustomTeamInfo.self)
|
||||
|
||||
@@ -736,7 +669,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.customPlayers.total { $0.score })
|
||||
.annotated(with: Team.customPlayers.total(Column("score")))
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: CustomTeamInfo.self)
|
||||
|
||||
@@ -773,10 +706,10 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.customPlayers.average { $0.score })
|
||||
.annotated(with: Team.customPlayers.average(Column("score")))
|
||||
.annotated(with: Team.customPlayers.count)
|
||||
.annotated(with: Team.customPlayers.min { $0.score }, Team.customPlayers.max { $0.score })
|
||||
.annotated(with: Team.customPlayers.sum { $0.score })
|
||||
.annotated(with: Team.customPlayers.min(Column("score")), Team.customPlayers.max(Column("score")))
|
||||
.annotated(with: Team.customPlayers.sum(Column("score")))
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: CustomTeamInfo.self)
|
||||
|
||||
@@ -834,11 +767,11 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.players.average { $0.score }.forKey("a1"))
|
||||
.annotated(with: Team.players.average(Column("score")).forKey("a1"))
|
||||
.annotated(with: Team.players.count.forKey("a2"))
|
||||
.annotated(with: Team.players.max { $0.score }.forKey("a3"))
|
||||
.annotated(with: Team.players.min { $0.score }.forKey("a4"))
|
||||
.annotated(with: Team.players.sum { $0.score }.forKey("a5"))
|
||||
.annotated(with: Team.players.max(Column("score")).forKey("a3"))
|
||||
.annotated(with: Team.players.min(Column("score")).forKey("a4"))
|
||||
.annotated(with: Team.players.sum(Column("score")).forKey("a5"))
|
||||
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "team".*, \
|
||||
@@ -858,10 +791,10 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.players.average { $0.score * $0.score }.forKey("a1"))
|
||||
.annotated(with: Team.players.max { $0.score * 10 }.forKey("a3"))
|
||||
.annotated(with: Team.players.min { -$0.score }.forKey("a4"))
|
||||
.annotated(with: Team.players.sum { $0.score * $0.score }.forKey("a5"))
|
||||
.annotated(with: Team.players.average(Column("score") * Column("score")).forKey("a1"))
|
||||
.annotated(with: Team.players.max(Column("score") * 10).forKey("a3"))
|
||||
.annotated(with: Team.players.min(-Column("score")).forKey("a4"))
|
||||
.annotated(with: Team.players.sum(Column("score") * Column("score")).forKey("a5"))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "team".*, \
|
||||
AVG("player"."score" * "player"."score") AS "a1", \
|
||||
@@ -884,8 +817,8 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.players.filter { $0.score < 500 }.forKey("lowPlayers").count)
|
||||
.annotated(with: Team.players.filter { $0.score >= 500 }.forKey("highPlayers").count)
|
||||
.annotated(with: Team.players.filter(Column("score") < 500).forKey("lowPlayers").count)
|
||||
.annotated(with: Team.players.filter(Column("score") >= 500).forKey("highPlayers").count)
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: TeamInfo.self)
|
||||
|
||||
@@ -1521,7 +1454,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
let request = Team
|
||||
.annotated(with: Team.players.min { $0.score } ?? 0)
|
||||
.annotated(with: Team.players.min(Column("score")) ?? 0)
|
||||
.orderByPrimaryKey()
|
||||
.asRequest(of: TeamInfo.self)
|
||||
|
||||
@@ -1558,7 +1491,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
do {
|
||||
let request = Team.annotated(with: abs(Team.players.max { $0.score }))
|
||||
let request = Team.annotated(with: abs(Team.players.max(Column("score"))))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "team".*, ABS(MAX("player"."score")) \
|
||||
FROM "team" \
|
||||
@@ -1567,7 +1500,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
""")
|
||||
}
|
||||
do {
|
||||
let request = Team.annotated(with: abs(Team.players.max { $0.score }).forKey("foo"))
|
||||
let request = Team.annotated(with: abs(Team.players.max(Column("score"))).forKey("foo"))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "team".*, ABS(MAX("player"."score")) AS "foo" \
|
||||
FROM "team" \
|
||||
@@ -1607,7 +1540,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
try dbQueue.read { db in
|
||||
do {
|
||||
// This is a meaningless request, but this is enough for this test
|
||||
let request = Team.annotated(with: length(Team.players.max { $0.score }))
|
||||
let request = Team.annotated(with: length(Team.players.max(Column("score"))))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "team".*, LENGTH(MAX("player"."score")) \
|
||||
FROM "team" \
|
||||
@@ -1617,7 +1550,7 @@ class AssociationAggregateTests: GRDBTestCase {
|
||||
}
|
||||
do {
|
||||
// This is a meaningless request, but this is enough for this test
|
||||
let request = Team.annotated(with: length(Team.players.max { $0.score }).forKey("foo"))
|
||||
let request = Team.annotated(with: length(Team.players.max(Column("score"))).forKey("foo"))
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "team".*, LENGTH(MAX("player"."score")) AS "foo" \
|
||||
FROM "team" \
|
||||
|
||||
@@ -5,11 +5,6 @@ private struct Team: Codable, FetchableRecord, PersistableRecord {
|
||||
static let databaseTableName = "teams"
|
||||
var id: Int64
|
||||
var name: String
|
||||
|
||||
enum Columns {
|
||||
static let id = Column(CodingKeys.id)
|
||||
static let name = Column(CodingKeys.name)
|
||||
}
|
||||
}
|
||||
|
||||
private struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
@@ -18,10 +13,6 @@ private struct Player: Codable, FetchableRecord, PersistableRecord {
|
||||
var id: Int64
|
||||
var teamId: Int64?
|
||||
var name: String
|
||||
|
||||
enum Columns {
|
||||
static let name = Column(CodingKeys.name)
|
||||
}
|
||||
}
|
||||
|
||||
private struct PlayerWithRequiredTeam: Decodable, FetchableRecord {
|
||||
@@ -43,24 +34,14 @@ private struct PlayerWithTeamName: Decodable, FetchableRecord {
|
||||
|
||||
private extension QueryInterfaceRequest<Player> {
|
||||
func filter(teamName: String) -> QueryInterfaceRequest<Player> {
|
||||
joining(required: PlayerWithOptionalTeam.team.filter { $0.name == teamName })
|
||||
joining(required: PlayerWithOptionalTeam.team.filter(Column("name") == teamName))
|
||||
}
|
||||
|
||||
func orderedByTeamName() -> QueryInterfaceRequest<Player> {
|
||||
let teamAlias = TableAlias()
|
||||
return self
|
||||
.joining(optional: PlayerWithOptionalTeam.team.aliased(teamAlias))
|
||||
.order { [teamAlias[Team.Columns.name], $0.name] }
|
||||
return joining(optional: PlayerWithOptionalTeam.team.aliased(teamAlias))
|
||||
.order(teamAlias[Column("name")], Column("name"))
|
||||
}
|
||||
|
||||
#if compiler(>=6.1)
|
||||
func orderedByTeamName_swift61() -> QueryInterfaceRequest<Player> {
|
||||
let teamAlias = TableAlias<Team>()
|
||||
return self
|
||||
.joining(optional: PlayerWithOptionalTeam.team.aliased(teamAlias))
|
||||
.order { [teamAlias.name, $0.name] }
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Test support for Decodable records
|
||||
@@ -101,7 +82,7 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase {
|
||||
func testAnnotatedWithRequired() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player
|
||||
.annotated(withRequired: Player.team.select { $0.name.forKey("teamName") })
|
||||
.annotated(withRequired: Player.team.select(Column("name").forKey("teamName")))
|
||||
.asRequest(of: PlayerWithTeamName.self)
|
||||
let records = try dbQueue.inDatabase { try request.fetchAll($0) }
|
||||
XCTAssertEqual(records.count, 1)
|
||||
@@ -132,7 +113,7 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase {
|
||||
func testAnnotatedWithOptional() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player
|
||||
.annotated(withOptional: Player.team.select { $0.name.forKey("teamName") })
|
||||
.annotated(withOptional: Player.team.select(Column("name").forKey("teamName")))
|
||||
.asRequest(of: PlayerWithTeamName.self)
|
||||
let records = try dbQueue.inDatabase { try request.fetchAll($0) }
|
||||
XCTAssertEqual(records.count, 2)
|
||||
@@ -171,7 +152,7 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase {
|
||||
func testRequestRefining() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player
|
||||
.including(required: PlayerWithRequiredTeam.team.select { [$0.name, $0.id] })
|
||||
.including(required: PlayerWithRequiredTeam.team.select(Column("name"), Column("id")))
|
||||
.filter(teamName: "Reds")
|
||||
.orderedByTeamName()
|
||||
.asRequest(of: PlayerWithRequiredTeam.self)
|
||||
@@ -189,28 +170,4 @@ class AssociationBelongsToDecodableRecordTests: GRDBTestCase {
|
||||
XCTAssertEqual(records[0].team.id, 1)
|
||||
XCTAssertEqual(records[0].team.name, "Reds")
|
||||
}
|
||||
|
||||
#if compiler(>=6.1)
|
||||
func testRequestRefining_swift61() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
let request = Player
|
||||
.including(required: PlayerWithRequiredTeam.team.select { [$0.name, $0.id] })
|
||||
.filter(teamName: "Reds")
|
||||
.orderedByTeamName_swift61()
|
||||
.asRequest(of: PlayerWithRequiredTeam.self)
|
||||
let records = try dbQueue.inDatabase { try request.fetchAll($0) }
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
SELECT "players".*, "teams"."name", "teams"."id" \
|
||||
FROM "players" \
|
||||
JOIN "teams" ON ("teams"."id" = "players"."teamId") AND ("teams"."name" = 'Reds') \
|
||||
ORDER BY "teams"."name", "players"."name"
|
||||
""")
|
||||
XCTAssertEqual(records.count, 1)
|
||||
XCTAssertEqual(records[0].player.id, 1)
|
||||
XCTAssertEqual(records[0].player.teamId, 1)
|
||||
XCTAssertEqual(records[0].player.name, "Arthur")
|
||||
XCTAssertEqual(records[0].team.id, 1)
|
||||
XCTAssertEqual(records[0].team.name, "Reds")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -22,10 +22,7 @@ private struct PlayerWithRequiredTeam: FetchableRecord {
|
||||
|
||||
init(row: Row) throws {
|
||||
player = try Player(row: row)
|
||||
let subscriptTeam: Team = row[Player.teamScope]
|
||||
let decodedTeam: Team = try row.decode(forKey: Player.teamScope)
|
||||
XCTAssertEqual(subscriptTeam.id, decodedTeam.id)
|
||||
team = subscriptTeam
|
||||
team = row[Player.teamScope]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,10 +32,7 @@ private struct PlayerWithOptionalTeam: FetchableRecord {
|
||||
|
||||
init(row: Row) throws {
|
||||
player = try Player(row: row)
|
||||
let subscriptTeam: Team? = row[Player.teamScope]
|
||||
let decodedTeam: Team? = try row.decodeIfPresent(forKey: Player.teamScope)
|
||||
XCTAssertEqual(subscriptTeam?.id, decodedTeam?.id)
|
||||
team = subscriptTeam
|
||||
team = row[Player.teamScope]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,21 +8,11 @@ private struct A : TableRecord {
|
||||
static let restrictedB1 = belongsTo(RestrictedB1.self)
|
||||
static let restrictedB2 = belongsTo(RestrictedB2.self)
|
||||
static let extendedB = belongsTo(ExtendedB.self)
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let bid = Column("idb")
|
||||
}
|
||||
}
|
||||
|
||||
private struct B : TableRecord {
|
||||
static let a = hasOne(A.self)
|
||||
static let databaseTableName = "b"
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
}
|
||||
}
|
||||
|
||||
private struct RestrictedB1 : TableRecord {
|
||||
@@ -119,23 +109,6 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
|
||||
JOIN "b" ON "b"."id" = "a"."bid"
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let aAlias = TableAlias<A>()
|
||||
let request = A
|
||||
.aliased(aAlias)
|
||||
.including(required: A.b
|
||||
.select { [
|
||||
$0.name,
|
||||
($0.id + aAlias.id).forKey("foo")
|
||||
] })
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."id" = "a"."bid"
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -178,20 +151,6 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
|
||||
JOIN "b" ON ("b"."id" = "a"."bid") AND ("b"."id" IN ("a"."id", "b"."id", 42))
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let alias = TableAlias<A>()
|
||||
let request = A
|
||||
.aliased(alias)
|
||||
.including(required: A.b
|
||||
.filter { [alias.id, $0.id, 42].contains($0.id) })
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON ("b"."id" = "a"."bid") AND ("b"."id" IN ("a"."id", "b"."id", 42))
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
do {
|
||||
let request = A.including(required: A.b.filter(key: ["id": 1]))
|
||||
try assertEqualSQL(db, request, """
|
||||
@@ -225,32 +184,16 @@ class AssociationBelongsToSQLDerivationTests: GRDBTestCase {
|
||||
func testFilterAssociationInWhereClause() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
let bAlias = TableAlias()
|
||||
let request = A
|
||||
.including(required: A.b.aliased(bAlias))
|
||||
.filter(bAlias[Column("name")] != nil)
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."id" = "a"."bid" \
|
||||
WHERE "b"."name" IS NOT NULL
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let bAlias = TableAlias<B>()
|
||||
let request = A
|
||||
.including(required: A.b.aliased(bAlias))
|
||||
.filter { _ in bAlias.name != nil }
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."id" = "a"."bid" \
|
||||
WHERE "b"."name" IS NOT NULL
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
let bAlias = TableAlias()
|
||||
let request = A
|
||||
.including(required: A.b.aliased(bAlias))
|
||||
.filter(bAlias[Column("name")] != nil)
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."id" = "a"."bid" \
|
||||
WHERE "b"."name" IS NOT NULL
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,21 +8,11 @@ private struct A : TableRecord {
|
||||
static let restrictedB1 = hasOne(RestrictedB1.self)
|
||||
static let restrictedB2 = hasOne(RestrictedB2.self)
|
||||
static let extendedB = hasOne(ExtendedB.self)
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
}
|
||||
}
|
||||
|
||||
private struct B : TableRecord {
|
||||
static let a = belongsTo(A.self)
|
||||
static let databaseTableName = "b"
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let aid = Column("aid")
|
||||
static let name = Column("name")
|
||||
}
|
||||
}
|
||||
|
||||
private struct RestrictedB1 : TableRecord {
|
||||
@@ -119,23 +109,6 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
|
||||
JOIN "b" ON "b"."aid" = "a"."id"
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let aAlias = TableAlias<A>()
|
||||
let request = A
|
||||
.aliased(aAlias)
|
||||
.including(required: A.b
|
||||
.select { [
|
||||
$0.name,
|
||||
($0.id + aAlias.id).forKey("foo"),
|
||||
] })
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."aid" = "a"."id"
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,32 +172,16 @@ class AssociationHasOneSQLDerivationTests: GRDBTestCase {
|
||||
func testFilterAssociationInWhereClause() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
let bAlias = TableAlias()
|
||||
let request = A
|
||||
.including(required: A.b.aliased(bAlias))
|
||||
.filter(bAlias[Column("name")] != nil)
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."aid" = "a"."id" \
|
||||
WHERE "b"."name" IS NOT NULL
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let bAlias = TableAlias<B>()
|
||||
let request = A
|
||||
.including(required: A.b.aliased(bAlias))
|
||||
.filter { _ in bAlias.name != nil }
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."aid" = "a"."id" \
|
||||
WHERE "b"."name" IS NOT NULL
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
let bAlias = TableAlias()
|
||||
let request = A
|
||||
.including(required: A.b.aliased(bAlias))
|
||||
.filter(bAlias[Column("name")] != nil)
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "b".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."aid" = "a"."id" \
|
||||
WHERE "b"."name" IS NOT NULL
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -7,11 +7,6 @@ private struct A: TableRecord {
|
||||
static let restrictedC1 = hasOne(RestrictedC1.self, through: b, using: B.restrictedC1)
|
||||
static let restrictedC2 = hasOne(RestrictedC2.self, through: b, using: B.restrictedC2)
|
||||
static let extendedC = hasOne(ExtendedC.self, through: b, using: B.extendedC)
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let bid = Column("bid")
|
||||
}
|
||||
}
|
||||
|
||||
private struct B: TableRecord {
|
||||
@@ -19,18 +14,9 @@ private struct B: TableRecord {
|
||||
static let restrictedC1 = belongsTo(RestrictedC1.self)
|
||||
static let restrictedC2 = belongsTo(RestrictedC2.self)
|
||||
static let extendedC = belongsTo(ExtendedC.self)
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let cid = Column("cid")
|
||||
}
|
||||
}
|
||||
|
||||
private struct C: TableRecord {
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let name = Column("name")
|
||||
}
|
||||
}
|
||||
|
||||
private struct RestrictedC1 : TableRecord {
|
||||
@@ -138,24 +124,6 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase {
|
||||
JOIN "c" ON "c"."id" = "b"."cId"
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let aAlias = TableAlias<A>()
|
||||
let request = A
|
||||
.aliased(aAlias)
|
||||
.including(required: A.c
|
||||
.select { [
|
||||
$0.name,
|
||||
($0.id + aAlias.id).forKey("foo")
|
||||
] })
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "c"."name", "c"."id" + "a"."id" AS "foo" \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."id" = "a"."bId" \
|
||||
JOIN "c" ON "c"."id" = "b"."cId"
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,34 +193,17 @@ class AssociationHasOneThroughSQLDerivationTests: GRDBTestCase {
|
||||
func testFilterAssociationInWhereClause() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
let cAlias = TableAlias()
|
||||
let request = A
|
||||
.including(required: A.c.aliased(cAlias))
|
||||
.filter(cAlias[Column("name")] != nil)
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "c".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."id" = "a"."bId" \
|
||||
JOIN "c" ON "c"."id" = "b"."cId" \
|
||||
WHERE "c"."name" IS NOT NULL
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let cAlias = TableAlias<C>()
|
||||
let request = A
|
||||
.including(required: A.c.aliased(cAlias))
|
||||
.filter { _ in cAlias.name != nil }
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "c".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."id" = "a"."bId" \
|
||||
JOIN "c" ON "c"."id" = "b"."cId" \
|
||||
WHERE "c"."name" IS NOT NULL
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
let cAlias = TableAlias()
|
||||
let request = A
|
||||
.including(required: A.c.aliased(cAlias))
|
||||
.filter(cAlias[Column("name")] != nil)
|
||||
try assertEqualSQL(db, request, """
|
||||
SELECT "a".*, "c".* \
|
||||
FROM "a" \
|
||||
JOIN "b" ON "b"."id" = "a"."bId" \
|
||||
JOIN "c" ON "c"."id" = "b"."cId" \
|
||||
WHERE "c"."name" IS NOT NULL
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -157,6 +157,110 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasMany_limit() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
// Plain request
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_bs_limited" AS (\
|
||||
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
|
||||
FROM "b" \
|
||||
WHERE "colb2" IN (1, 2, 3)\
|
||||
) \
|
||||
SELECT * FROM "grdb_bs_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colb1"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with avoided prefetch
|
||||
do {
|
||||
let request = A
|
||||
.none()
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM \"a\" WHERE 0 ORDER BY \"cola1\"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with filters
|
||||
do {
|
||||
let request = A
|
||||
.filter(Column("cola1") != 3)
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.filter(Column("colb1") == 4)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("bs1")
|
||||
.limit(3))
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.filter(Column("colb1") != 4)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("bs2")
|
||||
.limit(5, offset: 2))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" \
|
||||
WHERE "cola1" <> 3 \
|
||||
ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_bs1_limited" AS (\
|
||||
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
|
||||
FROM "b" \
|
||||
WHERE ("colb1" = 4) AND ("colb2" IN (1, 2))\
|
||||
) \
|
||||
SELECT * FROM "grdb_bs1_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colb1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_bs2_limited" AS (\
|
||||
SELECT *, "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb1") AS "rowNumber" \
|
||||
FROM "b" \
|
||||
WHERE ("colb1" <> 4) AND ("colb2" IN (1, 2))\
|
||||
) \
|
||||
SELECT * FROM "grdb_bs2_limited" \
|
||||
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8) \
|
||||
ORDER BY "colb1"
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyScalar() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
@@ -188,6 +292,42 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyScalar_limit() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
// Plain request
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(B.self)
|
||||
.select(Column("colb2"))
|
||||
.distinct()
|
||||
.order(Column("colb2"))
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_bs_limited" AS (\
|
||||
SELECT DISTINCT "colb2", "colb2" AS "grdb_colb2", ROW_NUMBER() OVER (PARTITION BY "colb2" ORDER BY "colb2") AS "rowNumber" \
|
||||
FROM "b" \
|
||||
WHERE "colb2" IN (1, 2, 3)\
|
||||
) \
|
||||
SELECT * FROM "grdb_bs_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colb2"
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyWithCompoundForeignKey() throws {
|
||||
// We can use the CTE technique
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
@@ -304,6 +444,141 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyWithCompoundForeignKey_limit() throws {
|
||||
// We can use the CTE technique
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
try db.create(table: "parent") { t in
|
||||
t.column("parentA", .text)
|
||||
t.column("parentB", .text)
|
||||
t.primaryKey(["parentA", "parentB"])
|
||||
}
|
||||
try db.create(table: "child") { t in
|
||||
t.column("pA", .text)
|
||||
t.column("pB", .text)
|
||||
t.column("name", .text)
|
||||
t.foreignKey(["pA", "pB"], references: "parent")
|
||||
}
|
||||
try db.execute(sql: """
|
||||
INSERT INTO parent (parentA, parentB) VALUES ('foo', 'bar');
|
||||
INSERT INTO parent (parentA, parentB) VALUES ('baz', 'qux');
|
||||
INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar1');
|
||||
INSERT INTO child (pA, pB, name) VALUES ('foo', 'bar', 'foobar2');
|
||||
INSERT INTO child (pA, pB, name) VALUES ('baz', 'qux', 'bazqux1');
|
||||
""")
|
||||
|
||||
struct Parent: TableRecord { }
|
||||
struct Child: TableRecord { }
|
||||
|
||||
// Plain request
|
||||
do {
|
||||
let request = Parent
|
||||
.including(all: Parent
|
||||
.hasMany(Child.self)
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" ORDER BY "parentA", "parentB"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_children_limited" AS (\
|
||||
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
|
||||
FROM "child" \
|
||||
WHERE ("pA", "pB") IN "grdb_base"\
|
||||
), \
|
||||
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent") \
|
||||
SELECT * \
|
||||
FROM "grdb_children_limited" \
|
||||
WHERE "rowNumber" <= 3
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with avoided prefetch
|
||||
do {
|
||||
let request = Parent
|
||||
.none()
|
||||
.including(all: Parent
|
||||
.hasMany(Child.self)
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" WHERE 0 ORDER BY "parentA", "parentB"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with filters
|
||||
do {
|
||||
let request = Parent
|
||||
.including(all: Parent
|
||||
.hasMany(Child.self)
|
||||
.filter(Column("name") == "foo")
|
||||
.limit(3))
|
||||
.filter(Column("parentA") == "foo")
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" WHERE "parentA" = 'foo' ORDER BY "parentA", "parentB"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_children_limited" AS (\
|
||||
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
|
||||
FROM "child" \
|
||||
WHERE ("name" = 'foo') AND (("pA", "pB") IN "grdb_base")\
|
||||
), \
|
||||
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" WHERE "parentA" = 'foo') \
|
||||
SELECT * \
|
||||
FROM "grdb_children_limited" \
|
||||
WHERE "rowNumber" <= 3
|
||||
"""])
|
||||
}
|
||||
|
||||
// Limited ordered request (preserve both ordering and limit in the CTE)
|
||||
do {
|
||||
let request = Parent
|
||||
.including(all: Parent
|
||||
.hasMany(Child.self)
|
||||
.limit(5, offset: 2))
|
||||
.orderByPrimaryKey()
|
||||
.limit(1)
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_children_limited" AS (\
|
||||
SELECT *, "pA" AS "grdb_pA", "pB" AS "grdb_pB", ROW_NUMBER() OVER (PARTITION BY "pA", "pB") AS "rowNumber" \
|
||||
FROM "child" WHERE ("pA", "pB") IN "grdb_base"\
|
||||
), \
|
||||
"grdb_base" AS (SELECT "parentA", "parentB" FROM "parent" ORDER BY "parentA", "parentB" LIMIT 1) \
|
||||
SELECT * FROM "grdb_children_limited" \
|
||||
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8)
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyIncludingAllHasMany() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
@@ -455,6 +730,218 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyIncludingAllHasMany_limit() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
// Plain request
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.orderByPrimaryKey()
|
||||
.limit(5, offset: 2))
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_cs_limited" AS (\
|
||||
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" ORDER BY "colc1") AS "rowNumber" \
|
||||
FROM "c" \
|
||||
WHERE "colc2" IN (1, 2, 3)\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_cs_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colc1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE "cold2" IN (7, 8, 9)\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds_limited" \
|
||||
WHERE ("rowNumber" >= 3) AND ("rowNumber" < 8) \
|
||||
ORDER BY "cold1"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with avoided second-level prefetch
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.none()
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.orderByPrimaryKey()
|
||||
.limit(5, offset: 2))
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_cs_limited" AS (\
|
||||
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" ORDER BY "colc1") AS "rowNumber" \
|
||||
FROM "c" \
|
||||
WHERE 0 AND ("colc2" IN (1, 2, 3))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_cs_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colc1"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with filters
|
||||
do {
|
||||
let request = A
|
||||
.filter(Column("cola1") != 3)
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.filter(Column("colc1") > 7)
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") == 11)
|
||||
.orderByPrimaryKey()
|
||||
.limit(1)
|
||||
.forKey("ds1"))
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") != 11)
|
||||
.orderByPrimaryKey()
|
||||
.limit(2)
|
||||
.forKey("ds2"))
|
||||
.orderByPrimaryKey()
|
||||
.limit(3)
|
||||
.forKey("cs1"))
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.filter(Column("colc1") < 9)
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") == 11)
|
||||
.orderByPrimaryKey()
|
||||
.limit(3)
|
||||
.forKey("ds1"))
|
||||
.including(all: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") != 11)
|
||||
.orderByPrimaryKey()
|
||||
.limit(4)
|
||||
.forKey("ds2"))
|
||||
.orderByPrimaryKey()
|
||||
.limit(5)
|
||||
.forKey("cs2"))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * \
|
||||
FROM "a" \
|
||||
WHERE "cola1" <> 3 \
|
||||
ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_cs1_limited" AS (\
|
||||
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" \
|
||||
ORDER BY "colc1") AS "rowNumber" \
|
||||
FROM "c" \
|
||||
WHERE ("colc1" > 7) AND ("colc2" IN (1, 2))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_cs1_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "colc1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds1_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
|
||||
ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE ("cold1" = 11) AND ("cold2" IN (8, 9))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds1_limited" \
|
||||
WHERE "rowNumber" <= 1 \
|
||||
ORDER BY "cold1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds2_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
|
||||
ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE ("cold1" <> 11) AND ("cold2" IN (8, 9))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds2_limited" \
|
||||
WHERE "rowNumber" <= 2 \
|
||||
ORDER BY "cold1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_cs2_limited" AS (\
|
||||
SELECT *, "colc2" AS "grdb_colc2", ROW_NUMBER() OVER (PARTITION BY "colc2" \
|
||||
ORDER BY "colc1") AS "rowNumber" \
|
||||
FROM "c" \
|
||||
WHERE ("colc1" < 9) AND ("colc2" IN (1, 2))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_cs2_limited" \
|
||||
WHERE "rowNumber" <= 5 \
|
||||
ORDER BY "colc1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds1_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
|
||||
ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE ("cold1" = 11) AND ("cold2" IN (7, 8))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds1_limited" \
|
||||
WHERE "rowNumber" <= 3 \
|
||||
ORDER BY "cold1"
|
||||
""",
|
||||
"""
|
||||
WITH "grdb_ds2_limited" AS (\
|
||||
SELECT *, "cold2" AS "grdb_cold2", ROW_NUMBER() OVER (PARTITION BY "cold2" \
|
||||
ORDER BY "cold1") AS "rowNumber" \
|
||||
FROM "d" \
|
||||
WHERE ("cold1" <> 11) AND ("cold2" IN (7, 8))\
|
||||
) \
|
||||
SELECT * \
|
||||
FROM "grdb_ds2_limited" \
|
||||
WHERE "rowNumber" <= 4 \
|
||||
ORDER BY "cold1"
|
||||
""",
|
||||
])}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyIncludingAllHasManyWithCompoundForeignKey() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.write { db in
|
||||
@@ -730,6 +1217,138 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyIncludingRequiredOrOptionalHasMany_limit() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
// Plain request
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.including(required: C
|
||||
.hasMany(D.self)
|
||||
.orderByPrimaryKey())
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
#warning("TODO: ordering on D is lost")
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d".* \
|
||||
FROM "c" \
|
||||
JOIN "d" ON "d"."cold2" = "c"."colc1" \
|
||||
WHERE "c"."colc2" IN (1, 2, 3) \
|
||||
ORDER BY "c"."colc1", "d"."cold1"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with avoided prefetch
|
||||
do {
|
||||
let request = A
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.none()
|
||||
.including(required: C
|
||||
.hasMany(D.self)
|
||||
.orderByPrimaryKey())
|
||||
.orderByPrimaryKey()
|
||||
.limit(3))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * FROM "a" ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d".* \
|
||||
FROM "c" \
|
||||
JOIN "d" ON "d"."cold2" = "c"."colc1" \
|
||||
WHERE 0 AND ("c"."colc2" IN (1, 2, 3)) \
|
||||
ORDER BY "c"."colc1", "d"."cold1"
|
||||
"""])
|
||||
}
|
||||
|
||||
// Request with filters
|
||||
do {
|
||||
let request = A
|
||||
.filter(Column("cola1") != 3)
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.filter(Column("colc1") > 7)
|
||||
.including(optional: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") == 11)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("d1"))
|
||||
.including(required: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") != 11)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("d2"))
|
||||
.orderByPrimaryKey()
|
||||
.limit(3)
|
||||
.forKey("cs1"))
|
||||
.including(all: A
|
||||
.hasMany(C.self)
|
||||
.filter(Column("colc1") < 9)
|
||||
.including(optional: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") == 11)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("d1"))
|
||||
.including(required: C
|
||||
.hasMany(D.self)
|
||||
.filter(Column("cold1") != 11)
|
||||
.orderByPrimaryKey()
|
||||
.forKey("d2"))
|
||||
.orderByPrimaryKey()
|
||||
.limit(3)
|
||||
.forKey("cs2"))
|
||||
.orderByPrimaryKey()
|
||||
|
||||
clearSQLQueries()
|
||||
_ = try Row.fetchAll(db, request)
|
||||
|
||||
let selectQueries = sqlQueries.filter(isSelectQuery)
|
||||
XCTAssertEqual(selectQueries, [
|
||||
"""
|
||||
SELECT * \
|
||||
FROM "a" \
|
||||
WHERE "cola1" <> 3 \
|
||||
ORDER BY "cola1"
|
||||
""",
|
||||
"""
|
||||
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d1".*, "d2".* \
|
||||
FROM "c" \
|
||||
LEFT JOIN "d" "d1" ON ("d1"."cold2" = "c"."colc1") AND ("d1"."cold1" = 11) \
|
||||
JOIN "d" "d2" ON ("d2"."cold2" = "c"."colc1") AND ("d2"."cold1" <> 11) \
|
||||
WHERE ("c"."colc1" > 7) AND ("c"."colc2" IN (1, 2)) \
|
||||
ORDER BY "c"."colc1", "d1"."cold1", "d2"."cold1"
|
||||
""",
|
||||
"""
|
||||
SELECT "c".*, "c"."colc2" AS "grdb_colc2", "d1".*, "d2".* \
|
||||
FROM "c" \
|
||||
LEFT JOIN "d" "d1" ON ("d1"."cold2" = "c"."colc1") AND ("d1"."cold1" = 11) \
|
||||
JOIN "d" "d2" ON ("d2"."cold2" = "c"."colc1") AND ("d2"."cold1" <> 11) \
|
||||
WHERE ("c"."colc1" < 9) AND ("c"."colc2" IN (1, 2)) \
|
||||
ORDER BY "c"."colc1", "d1"."cold1", "d2"."cold1"
|
||||
"""])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testIncludingAllHasManyThroughHasManyUsingHasMany() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.read { db in
|
||||
|
||||
@@ -10,23 +10,11 @@ private struct A : TableRecord {
|
||||
static let child = hasOne(A.self)
|
||||
static let b1 = belongsTo(B.self, key: "b1", using: ForeignKey(["bid1"]))
|
||||
static let b2 = belongsTo(B.self, key: "b2", using: ForeignKey(["bid2"]))
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
static let bid1 = Column("bid1")
|
||||
static let bid2 = Column("bid2")
|
||||
static let parentId = Column("parentId")
|
||||
static let name = Column("name")
|
||||
}
|
||||
}
|
||||
private struct B : TableRecord {
|
||||
static let databaseTableName = "b"
|
||||
static let a1 = hasOne(A.self, key: "a1", using: ForeignKey(["bid1"]))
|
||||
static let a2 = hasOne(A.self, key: "a1", using: ForeignKey(["bid2"]))
|
||||
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
}
|
||||
}
|
||||
|
||||
/// Tests for table name conflicts, recursive associations,
|
||||
@@ -130,86 +118,6 @@ class AssociationTableAliasTestsSQLTests : GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
#if compiler(>=6.1)
|
||||
func testTableAliasBasics_swift61() throws {
|
||||
// A table reference qualifies all unqualified selectables, expressions, and orderings
|
||||
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
do {
|
||||
let alias = TableAlias<A>()
|
||||
|
||||
let expectedSQL = """
|
||||
SELECT "name" \
|
||||
FROM "a" \
|
||||
WHERE ("id" = 1) AND ("name" IS NOT NULL) AND ("name" = 'foo') \
|
||||
GROUP BY "name" \
|
||||
HAVING "name" \
|
||||
ORDER BY "name"
|
||||
"""
|
||||
|
||||
do {
|
||||
let request = A
|
||||
.aliased(alias)
|
||||
.select(\.name)
|
||||
.filter(key: 1)
|
||||
.filter { $0.name != nil && alias.name == "foo" }
|
||||
.group(\.name)
|
||||
.having(\.name)
|
||||
.order(\.name)
|
||||
try assertEqualSQL(db, request, expectedSQL)
|
||||
}
|
||||
do {
|
||||
let request = A
|
||||
.select(\.name)
|
||||
.filter(key: 1)
|
||||
.filter { $0.name != nil && alias.name == "foo" }
|
||||
.group(\.name)
|
||||
.having(\.name)
|
||||
.order(\.name)
|
||||
.aliased(alias)
|
||||
try assertEqualSQL(db, request, expectedSQL)
|
||||
}
|
||||
}
|
||||
do {
|
||||
let alias = TableAlias<A>(name: "customA")
|
||||
|
||||
let expectedSQL = """
|
||||
SELECT "customA"."name" \
|
||||
FROM "a" "customA" \
|
||||
WHERE ("customA"."id" = 1) AND ("customA"."name" IS NOT NULL) AND ("customA"."name" = 'foo') \
|
||||
GROUP BY "customA"."name" \
|
||||
HAVING "customA"."name" \
|
||||
ORDER BY "customA"."name"
|
||||
"""
|
||||
|
||||
do {
|
||||
let request = A
|
||||
.aliased(alias)
|
||||
.select(\.name)
|
||||
.filter(key: 1)
|
||||
.filter { $0.name != nil && alias.name == "foo" }
|
||||
.group(\.name)
|
||||
.having(\.name)
|
||||
.order(\.name)
|
||||
try assertEqualSQL(db, request, expectedSQL)
|
||||
}
|
||||
do {
|
||||
let request = A
|
||||
.select(\.name)
|
||||
.filter(key: 1)
|
||||
.filter { $0.name != nil && alias.name == "foo" }
|
||||
.group(\.name)
|
||||
.having(\.name)
|
||||
.order(\.name)
|
||||
.aliased(alias)
|
||||
try assertEqualSQL(db, request, expectedSQL)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
func testRecursiveRelationDepth1() throws {
|
||||
// A.include(A.parent)
|
||||
// A.include(A.child)
|
||||
|
||||
@@ -40,7 +40,7 @@ class ColumnExpressionTests: GRDBTestCase {
|
||||
|
||||
static var testRequest: QueryInterfaceRequest<Player> {
|
||||
// Test expression derivation
|
||||
filter { $0.name != nil }.order { $0.score.desc }
|
||||
return filter(Columns.name != nil).order(Columns.score.desc)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,10 +54,10 @@ class ColumnExpressionTests: GRDBTestCase {
|
||||
|
||||
// Test rowId column identification
|
||||
try XCTAssertEqual(Player.filter(key: 1).databaseRegion(db).description, "player(id,name,score)[1]")
|
||||
try XCTAssertEqual(Player.filter { $0.id == 1 }.databaseRegion(db).description, "player(id,name,score)[1]")
|
||||
try XCTAssertEqual(Player.filter { 1 == $0.id }.databaseRegion(db).description, "player(id,name,score)[1]")
|
||||
try XCTAssertEqual(Player.filter { $0.id == 1 || $0.id == 2 }.databaseRegion(db).description, "player(id,name,score)[1,2]")
|
||||
try XCTAssertEqual(Player.filter { [1, 2, 3].contains($0.id) }.databaseRegion(db).description, "player(id,name,score)[1,2,3]")
|
||||
try XCTAssertEqual(Player.filter(Player.Columns.id == 1).databaseRegion(db).description, "player(id,name,score)[1]")
|
||||
try XCTAssertEqual(Player.filter(1 == Player.Columns.id).databaseRegion(db).description, "player(id,name,score)[1]")
|
||||
try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).databaseRegion(db).description, "player(id,name,score)[1,2]")
|
||||
try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "player(id,name,score)[1,2,3]")
|
||||
|
||||
// Test specific column updates
|
||||
let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000])
|
||||
@@ -65,7 +65,8 @@ class ColumnExpressionTests: GRDBTestCase {
|
||||
XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1")
|
||||
|
||||
// Test compound expression
|
||||
let request = Player.select { $0.name == "foo" }
|
||||
let expression = Player.Columns.name == "foo"
|
||||
let request = Player.select(expression)
|
||||
try assertEqualSQL(db, request, "SELECT \"name\" = 'foo' FROM \"player\"")
|
||||
}
|
||||
}
|
||||
@@ -101,7 +102,7 @@ class ColumnExpressionTests: GRDBTestCase {
|
||||
|
||||
static var testRequest: QueryInterfaceRequest<Player> {
|
||||
// Test expression derivation
|
||||
filter { $0.name != nil }.order { $0.score.desc }
|
||||
return filter(Columns.name != nil).order(Columns.score.desc)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,10 +116,10 @@ class ColumnExpressionTests: GRDBTestCase {
|
||||
|
||||
// Test rowId column identification
|
||||
try XCTAssertEqual(Player.filter(key: 1).databaseRegion(db).description, "player(id,name,score)[1]")
|
||||
try XCTAssertEqual(Player.filter { $0.id == 1 }.databaseRegion(db).description, "player(id,name,score)[1]")
|
||||
try XCTAssertEqual(Player.filter { 1 == $0.id }.databaseRegion(db).description, "player(id,name,score)[1]")
|
||||
try XCTAssertEqual(Player.filter { $0.id == 1 || $0.id == 2 }.databaseRegion(db).description, "player(id,name,score)[1,2]")
|
||||
try XCTAssertEqual(Player.filter { [1, 2, 3].contains($0.id) }.databaseRegion(db).description, "player(id,name,score)[1,2,3]")
|
||||
try XCTAssertEqual(Player.filter(Player.Columns.id == 1).databaseRegion(db).description, "player(id,name,score)[1]")
|
||||
try XCTAssertEqual(Player.filter(1 == Player.Columns.id).databaseRegion(db).description, "player(id,name,score)[1]")
|
||||
try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).databaseRegion(db).description, "player(id,name,score)[1,2]")
|
||||
try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "player(id,name,score)[1,2,3]")
|
||||
|
||||
// Test specific column updates
|
||||
let player = Player(row: ["id": 1, "name": "Arthur", "score": 1000])
|
||||
@@ -126,7 +127,8 @@ class ColumnExpressionTests: GRDBTestCase {
|
||||
XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1")
|
||||
|
||||
// Test compound expression
|
||||
let request = Player.select { $0.name == "foo" }
|
||||
let expression = Player.Columns.name == "foo"
|
||||
let request = Player.select(expression)
|
||||
try assertEqualSQL(db, request, "SELECT \"name\" = 'foo' FROM \"player\"")
|
||||
}
|
||||
}
|
||||
@@ -156,7 +158,7 @@ class ColumnExpressionTests: GRDBTestCase {
|
||||
|
||||
static var testRequest: QueryInterfaceRequest<Player> {
|
||||
// Test expression derivation
|
||||
filter { $0.name != nil }.order { $0.score.desc }
|
||||
return filter(Columns.name != nil).order(Columns.score.desc)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,10 +172,10 @@ class ColumnExpressionTests: GRDBTestCase {
|
||||
|
||||
// Test rowId column identification
|
||||
try XCTAssertEqual(Player.filter(key: 1).databaseRegion(db).description, "player(full_name,id,score)[1]")
|
||||
try XCTAssertEqual(Player.filter { $0.id == 1 }.databaseRegion(db).description, "player(full_name,id,score)[1]")
|
||||
try XCTAssertEqual(Player.filter { 1 == $0.id }.databaseRegion(db).description, "player(full_name,id,score)[1]")
|
||||
try XCTAssertEqual(Player.filter { $0.id == 1 || $0.id == 2 }.databaseRegion(db).description, "player(full_name,id,score)[1,2]")
|
||||
try XCTAssertEqual(Player.filter { [1, 2, 3].contains($0.id) }.databaseRegion(db).description, "player(full_name,id,score)[1,2,3]")
|
||||
try XCTAssertEqual(Player.filter(Player.Columns.id == 1).databaseRegion(db).description, "player(full_name,id,score)[1]")
|
||||
try XCTAssertEqual(Player.filter(1 == Player.Columns.id).databaseRegion(db).description, "player(full_name,id,score)[1]")
|
||||
try XCTAssertEqual(Player.filter(Player.Columns.id == 1 || Player.Columns.id == 2).databaseRegion(db).description, "player(full_name,id,score)[1,2]")
|
||||
try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "player(full_name,id,score)[1,2,3]")
|
||||
|
||||
// Test specific column updates
|
||||
let player = try Player(row: ["id": 1, "full_name": "Arthur", "score": 1000])
|
||||
@@ -181,7 +183,8 @@ class ColumnExpressionTests: GRDBTestCase {
|
||||
XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"full_name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1")
|
||||
|
||||
// Test compound expression
|
||||
let request = Player.select { $0.name == "foo" }
|
||||
let expression = Player.Columns.name == "foo"
|
||||
let request = Player.select(expression)
|
||||
try assertEqualSQL(db, request, "SELECT \"full_name\" = 'foo' FROM \"player\"")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,12 +26,7 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
func testQuery() throws {
|
||||
struct T: TableRecord {
|
||||
enum Columns {
|
||||
static let id = Column("id")
|
||||
}
|
||||
}
|
||||
|
||||
struct T: TableRecord { }
|
||||
try makeDatabaseQueue().write { db in
|
||||
try db.create(table: "t") { t in
|
||||
t.autoIncrementedPrimaryKey("id")
|
||||
@@ -101,20 +96,6 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
LEFT JOIN "cte" ON "t"."id" > "cte"."id"
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let cte = CommonTableExpression<T>(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.including(optional: T.association(to: cte, on: { $0.id > $1.id }))
|
||||
try assertEqualSQL(db, request, """
|
||||
WITH "cte" AS (SELECT * FROM "t") \
|
||||
SELECT "t".*, "cte".* \
|
||||
FROM "t" \
|
||||
LEFT JOIN "cte" ON "t"."id" > "cte"."id"
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
|
||||
// Include SQL request as a CTE
|
||||
do {
|
||||
@@ -131,22 +112,6 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
JOIN "cte" ON "t"."id" = "cte"."id"
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
literal: "SELECT 1 as id")
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.including(required: T.association(to: cte, on: { $0.id == $1["id"] }))
|
||||
try assertEqualSQL(db, request, """
|
||||
WITH "cte" AS (SELECT 1 as id) \
|
||||
SELECT "t".*, "cte".* \
|
||||
FROM "t" \
|
||||
JOIN "cte" ON "t"."id" = "cte"."id"
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
|
||||
// Include a filtered SQL request as a CTE
|
||||
do {
|
||||
@@ -180,23 +145,6 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
JOIN "cte" ON "t"."id" = "cte"."id"
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
columns: [],
|
||||
literal: "SELECT 1 AS id")
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.including(required: T.association(to: cte, on: { $0.id == $1["id"] }))
|
||||
try assertEqualSQL(db, request, """
|
||||
WITH "cte" AS (SELECT 1 AS id) \
|
||||
SELECT "t".*, "cte".* \
|
||||
FROM "t" \
|
||||
JOIN "cte" ON "t"."id" = "cte"."id"
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
|
||||
// Include SQL request as a CTE (custom column name)
|
||||
do {
|
||||
@@ -214,23 +162,6 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
JOIN "cte" ON "t"."id" = "cte"."id"
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let cte = CommonTableExpression(
|
||||
named: "cte",
|
||||
columns: ["id", "a"],
|
||||
literal: "SELECT 1, 2")
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.including(required: T.association(to: cte, on: { $0.id == $1["id"] }))
|
||||
try assertEqualSQL(db, request, """
|
||||
WITH "cte"("id", "a") AS (SELECT 1, 2) \
|
||||
SELECT "t".*, "cte".* \
|
||||
FROM "t" \
|
||||
JOIN "cte" ON "t"."id" = "cte"."id"
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
|
||||
// Include SQL request as a CTE (empty ON clause)
|
||||
do {
|
||||
@@ -261,20 +192,6 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
JOIN "cte" ON "t"."id" > "cte"."id"
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let cte = CommonTableExpression<T>(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.joining(required: T.association(to: cte, on: { $0.id > $1.id }))
|
||||
try assertEqualSQL(db, request, """
|
||||
WITH "cte" AS (SELECT * FROM "t") \
|
||||
SELECT "t".* \
|
||||
FROM "t" \
|
||||
JOIN "cte" ON "t"."id" > "cte"."id"
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
|
||||
// Include filtered CTE
|
||||
do {
|
||||
@@ -336,21 +253,6 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
JOIN "cte" ON "t"."id" > "cte"."id"
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let cte = CommonTableExpression<T>(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.including(required: T.association(to: cte, on: { $0.id > $1.id }))
|
||||
.including(required: T.association(to: cte, on: { $0.id > $1.id }))
|
||||
try assertEqualSQL(db, request, """
|
||||
WITH "cte" AS (SELECT * FROM "t") \
|
||||
SELECT "t".*, "cte".* \
|
||||
FROM "t" \
|
||||
JOIN "cte" ON "t"."id" > "cte"."id"
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
|
||||
// Include one CTE twice with same key but different condition (last condition wins)
|
||||
do {
|
||||
@@ -366,21 +268,6 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
JOIN "cte" ON ("t"."id" + "cte"."id") = 1
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let cte = CommonTableExpression<T>(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.including(required: T.association(to: cte, on: { $0.id > $1.id }))
|
||||
.including(required: T.association(to: cte, on: { $0.id + $1.id == 1 }))
|
||||
try assertEqualSQL(db, request, """
|
||||
WITH "cte" AS (SELECT * FROM "t") \
|
||||
SELECT "t".*, "cte".* \
|
||||
FROM "t" \
|
||||
JOIN "cte" ON ("t"."id" + "cte"."id") = 1
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
|
||||
// Include one CTE twice with different keys
|
||||
do {
|
||||
@@ -397,22 +284,6 @@ class CommonTableExpressionTests: GRDBTestCase {
|
||||
JOIN "cte" "cte2" ON "t"."id" < "cte2"."id"
|
||||
""")
|
||||
}
|
||||
#if compiler(>=6.1)
|
||||
do {
|
||||
let cte = CommonTableExpression<T>(named: "cte", request: T.all())
|
||||
let request = T.all()
|
||||
.with(cte)
|
||||
.including(required: T.association(to: cte, on: { $0.id > $1.id }).forKey("a"))
|
||||
.including(required: T.association(to: cte, on: { $0.id < $1.id }).forKey("b"))
|
||||
try assertEqualSQL(db, request, """
|
||||
WITH "cte" AS (SELECT * FROM "t") \
|
||||
SELECT "t".*, "cte1".*, "cte2".* \
|
||||
FROM "t" \
|
||||
JOIN "cte" "cte1" ON "t"."id" > "cte1"."id" \
|
||||
JOIN "cte" "cte2" ON "t"."id" < "cte2"."id"
|
||||
""")
|
||||
}
|
||||
#endif
|
||||
|
||||
// Chain CTE includes
|
||||
do {
|
||||
|
||||
@@ -126,7 +126,7 @@ extension DatabaseDataDecodingStrategyTests {
|
||||
XCTFail("Unexpected Data")
|
||||
}
|
||||
} catch let error as RowDecodingError {
|
||||
switch error.impl {
|
||||
switch error {
|
||||
case .valueMismatch:
|
||||
XCTAssertEqual(error.description, """
|
||||
could not decode Data from database value "invalid" - \
|
||||
|
||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user