Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2021-03-12 17:47:50 +01:00
commit ae3c491661
41 files changed
+2776 -1245

No files matched your search

+21
View File
@@ -7,6 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 5.x Releases
- `5.6.x` Releases - [5.6.0](#560)
- `5.5.x` Releases - [5.5.0](#550)
- `5.4.x` Releases - [5.4.0](#540)
- `5.3.x` Releases - [5.3.0](#530)
@@ -71,6 +72,26 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- [0.110.0](#01100), ...
## 5.6.0
Released March 12, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.5.0...v5.6.0)
- **Fixed**: [#933](https://github.com/groue/GRDB.swift/pull/933): Fix DatabaseMigrator.eraseDatabaseOnSchemaChange in the context of shared databases
- **Fixed**: [#934](https://github.com/groue/GRDB.swift/pull/934): Fix a crash in the ValueObservation publisher
- **New**: [#936](https://github.com/groue/GRDB.swift/pull/936): Complete Associations and the DerivableRequest Protocol
- **New**: Database cursors can feed more standard Swift collections: `Array(cursor, minimumCapacity: ...)`, `Dictionary(uniqueKeysWithValues: cursor)`, etc (see [Cursors](README.md#cursors)).
- **Documentation update**: The [Associations Guide](Documentation/AssociationsBasics.md) has gained a new [Further Refinements to Associations](Documentation/AssociationsBasics.md#further-refinements-to-associations) chapter which shows the new association methods brought by [#936](https://github.com/groue/GRDB.swift/pull/936).
- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has an updated [Define Record Requests](Documentation/GoodPracticesForDesigningRecordTypes.md#define-record-requests) chapter, now that the `DerivableRequest` protocol has access to `limit`, `distinct`, `group`, `having`, association aggregates, and common table expressions.
- **Documentation update**: The [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) guide has a new chapter of good practices: [Record Types Hide Intimate Database Details](Documentation/GoodPracticesForDesigningRecordTypes.md#record-types-hide-intimate-database-details).
- **Documentation update**: A new [Single-Row Tables](Documentation/SingleRowTables.md) guide provides guidance for designing tables that store configuration values, user preferences, and generally some global application state.
## 5.5.0
Released March 3, 2021 • [diff](https://github.com/groue/GRDB.swift/compare/v5.4.0...v5.5.0)
+131 -2
View File
@@ -26,6 +26,7 @@ GRDB Associations
- [Sorting Associations]
- [Ordered Associations]
- [Columns Selected by an Association]
- [Further Refinements to Associations]
- [Table Aliases]
- [Refining Association Requests]
- [Fetching Values from Associations]
@@ -781,6 +782,7 @@ Fetch requests do not visit the database until you fetch values from them. This
- [Sorting Associations]
- [Ordered Associations]
- [Columns Selected by an Association]
- [Further Refinements to Associations]
- [Table Aliases]
- [Refining Association Requests]
@@ -855,14 +857,22 @@ Before we describe them in detail, let's see a few requests they can build:
let request = Author
.including(all: Author.books)
/// All authors with their three most popular books
let request = Author
.including(all: Author.books.order(Column("popularity").desc).limit(3))
/// All authors with their awarded books
let request = Author
.including(all: Author.books.having(Book.awards.isEmpty == false))
/// All books with their respective author
let request = Book
.including(required: Book.author)
/// All books with their respective author, sorted by title
let request = Book
.order(Column("title"))
.including(required: Book.author)
.order(Column("title"))
/// All books written by a French author
let request = Book
@@ -1235,7 +1245,6 @@ let teamInfos = try Team
.fetchAll(db)
```
## Columns Selected by an Association
By default, associated records include all their columns:
@@ -1262,6 +1271,124 @@ let request = Book.including(required: restrictedAuthor)
To specify the default selection for all inclusions of a given type, see [Columns Selected by a Request](../README.md#columns-selected-by-a-request).
## Further Refinements to Associations
Associations support more refinements:
- `limit`
Fetch all authors with their three most popular books:
```swift
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var books: [Book]
}
let mostPopularBooks = Author.books
.order(Column("popularity").desc)
.limit(3)
let authorInfos: [AuthorInfo] = try Author
.including(all: mostPopularBooks)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- `distinct`
Fetch all authors with the kinds of books they write (novels, poems, plays, etc):
```swift
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookKinds: Set<Book.Kind>
}
let distinctBookKinds = Author.books
.select(Column("kind"))
.distinct()
.forKey("bookKinds")
let authorInfos: [AuthorInfo] = try Author
.including(all: distinctBookKinds)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- `group`, `having`
Fetch all authors with the year of their latest book for each kind (novels, poems, plays, etc):
```swift
struct BookKindInfo: Decodable {
var kind: Book.Kind
var maxYear: Int
}
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookKindInfos: [BookKindInfo]
}
let bookKindInfos = Author.books
.select(
Column("kind"),
max(Column("year")).forKey("maxYear"))
.group(Column("kind"))
.forKey("bookKindInfos")
let authorInfos: [AuthorInfo] = try Author
.including(all: bookKindInfos)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- [Association Aggregates]
Fetch all authors with their awarded books:
```swift
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var awardedBooks: [Book]
}
let awardedBooks = Author.books
.having(Book.awards.isEmpty == false)
.forKey("awardedBooks")
let authorInfos: [AuthorInfo] = try Author
.including(all: awardedBooks)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
- [Common Table Expressions]
Association can use their own CTEs:
```swift
struct AuthorInfo: FetchableRecord, Decodable {
var author: Author
var specialBooks: [Book]
}
let specialCTE = CommonTableExpression(...)
let specialBooks = Author.books
.with(specialCTE)
... // use the CTE in the book association
.forKey("specialBooks")
let authorInfos = try Author
.including(all: specialBooks)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
```
> :warning: **Warning**: associations refined with `limit`, `distinct`, `group`, `having`, or association aggregates can only be used with `including(all:)`. You will get a fatal error if you use them with other joining methods: `including(required:)`, etc.
## Table Aliases
In all examples we have seen so far, all associated records are joined, included, filtered, and sorted independently. We could not filter them on conditions that involve several records, for example.
@@ -2447,6 +2574,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Choosing Between BelongsTo and HasOne]: #choosing-between-belongsto-and-hasone
[Self Joins]: #self-joins
[Ordered Associations]: #ordered-associations
[Further Refinements to Associations]: #further-refinements-to-associations
[The Types of Associations]: #the-types-of-associations
[FetchableRecord]: ../README.md#fetchablerecord-protocols
[migration]: Migrations.md
@@ -2497,4 +2625,5 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[ValueObservation]: ../README.md#valueobservation
[FAQ]: ../README.md#faq-associations
[common table expressions]: CommonTableExpressions.md
[Common Table Expressions]: CommonTableExpressions.md
[Associations to Common Table Expressions]: CommonTableExpressions.md#associations-to-common-table-expressions
+2 -2
View File
@@ -280,7 +280,7 @@ let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html):
FTS3Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.6/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -529,7 +529,7 @@ let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html):
FTS5Pattern are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/5.6/Structs/StatementArguments.html):
```swift
let documents = try Document.fetchAll(db,
@@ -9,6 +9,8 @@ To support this guide, we'll design a simple library application that lets the u
- [Trust SQLite More Than Yourself]
- [Persistable Record Types are Responsible for Their Tables]
- [Record Types Hide Intimate Database Details]
- [Singleton Records]
- [Define Record Requests]
- [Compose Records]
- [How to Design Database Managers]
@@ -139,11 +141,98 @@ That's it. The `Author` type can read and write in the `author` database table.
> }
> ```
Since `Author` and `Book` can insert, update, and delete rows in the `author` and `book` database tables, they are *responsible for modifying those database tables*.
Now that `Author` and `Book` can read and write in their own database tables, they are responsible for it. Make sure each record type deals with one database table, and only one database table!
Applying the **[Single Responsibility Principle]** has a consequence: don't even try to have an author responsible for its books. Don't add a `books: [Book]` property in Author. Don't let Author write in the `book` table. When a new fellow coworker joins your team and asks you "who is saving books in the database?", you don't want to answer "it depends." You want to confidently answer: "the Book type".
> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table.
## Record Types Hide Intimate Database Details
The application uses `Book` and `Author` as regular structs, using their properties. Each of those properties matches a column in the database (`Book.title`, `Author.id`), and is defined with a Swift type that is natively supported by SQLite (`String`, `Int`, etc.)
Sometimes, it happens that raw database column names and types are not a very good fit for the application.
Let's look at three examples:
1. Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. For easy debugging of the database contents, a book kind is represented as a string ("novel", "essay", etc.):
```swift
try db.create(table: "book") { t in
...
t.column("kind", .text).notNull()
}
```
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We want an enum instead:
```swift
struct Book: Codable {
enum Kind: String, Codable {
case novel, poems, essay, play
}
var id: Int64?
var authorId: Int64
var title: String
var kind: Kind
}
```
In order to make it possible to use `Book.Kind` in book requests (see [Define Record Requests] below), we add this conformance:
```swift
extension Book.Kind: DatabaseValueConvertible { }
```
> :bulb: Records can pick the best suited [Value] type for their column properties (Bool, Int, String, Date, etc.) Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database.
2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
When this happens, keep column properties private, and provide sensible accessors instead:
```swift
struct Place: Codable {
var id: Int64?
var name: String
private var latitude: CLLocationDegrees
private var longitude: CLLocationDegrees
var coordinate: CLLocationCoordinate2D {
get {
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
}
```
> :bulb: Private properties make it possible to hide raw columns from the rest of the application.
3. The record below exposes a `price: Decimal` property ($12.00), backed by an integer column that stores a quantity of cents (1200). An integer column is preferred because it allows SQLite to compute exact sums of prices.
```swift
struct Product: Codable {
var id: Int64?
var name: String
private var priceCents: Int
var price: Decimal {
get { Decimal(priceCents) / 100 }
set { priceCents = NSDecimalNumber(decimal: newValue * 100).intValue }
}
}
```
> :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface.
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#customizing-the-persistence-methods) before they enter the database.
## Singleton Records
**Singleton Records** are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row.
The recommended setup for such records is described in the [Single-Row Tables](SingleRowTables.md) guide. Go check it, and come back when you're done!
## Define Record Requests
@@ -166,7 +255,7 @@ extension Author {
}
```
Otherwise, declare a plain String enum that conforms to the ColumnExpression protocol:
Otherwise, declare a plain `String` enum that conforms to the `ColumnExpression` protocol:
```swift
// For a non-codable record
@@ -178,31 +267,50 @@ extension Author {
}
```
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
The `DerivableRequest` protocol generally lets you filter, sort, and join or include associations (we'll talk about associations in the [Compose Records] chapter below).
Here is how you define those requests:
Those columns let you define requests:
```swift
// Some requests of Author --------------------v
try dbQueue.read { db in
// Order authors by name, in a localized case-insensitive fashion
let sortedAuthors: [Author] = try Author.all()
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
.fetchAll(db)
// French authors
let frenchAuthors: [Author] = try Author.all()
.filter(Author.Columns.country == "France")
.fetchAll(db)
}
```
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
When you find yourself build similar requests over and over in your application, you may want to define a reusable and composable request vocabulary. This will avoid repetition in your app, ease refactoring, and enable [testability](DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift).
To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc:
```swift
// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~
extension DerivableRequest where RowDecoder == Author {
/// Returns a request for all authors ordered by name, in a localized
/// case-insensitive fashion
/// Order authors by name, in a localized case-insensitive fashion
func orderByName() -> Self {
let name = Author.Columns.name
return order(name.collating(.localizedCaseInsensitiveCompare))
}
/// Returns a request for all authors from a country
/// Filters authors from a country
func filter(country: String) -> Self {
filter(Author.Columns.country == country)
}
/// Filters authors with at least one book
func havingBooks() -> Self {
having(Author.books.isEmpty == false)
}
}
```
Those methods defined on the `DerivableRequest` protocol hide intimate database details. They allow you to compose database requests in a fluent style:
Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible style:
```swift
try dbQueue.read { db in
@@ -214,72 +322,55 @@ try dbQueue.read { db in
.filter(country: "France")
.fetchAll(db)
let sortedSpanishAuthors: [Author] = try Author.all()
let sortedSpanishAuthorsHavingBooks: [Author] = try Author.all()
.filter(country: "Spain")
.havingBooks()
.orderByName()
.fetchAll(db)
}
```
Those customized request methods are also available on record associations, because associations conform to the `DerivableRequest` protocol:
Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(authorCountry:)` for books, below, uses the `filter(country:)` for authors:
```swift
// Some requests of Book
// Book requests ~~~~~~~~~~~~~~~~~~~~~~~~
extension DerivableRequest where RowDecoder == Book {
/// Returns a request for all books from a country
/// Filters books by kind
func filter(kind: Book.Kind) -> Self {
filter(Book.Columns.kind == kind)
}
/// Filters books from a country
func filter(authorCountry: String) -> Self {
// A book is from a country if it can be
// joined with an author from that country:
// ---------------------------v
// Books do not have any country column. But their author has one.
// A book is from a country if it can be joined to an author from this country:
joining(required: Book.author.filter(country: authorCountry))
}
}
try dbQueue.read { db in
let italianBooks = try Book.all()
let italianNovels: [Book] = try Book.all()
.filter(kind: .novel)
.filter(authorCountry: "Italy")
.fetchAll(db)
}
```
Not *every requests* can be expressed on `DerivableRequest`. For example, [Association Aggregates] are out of scope. When this happens, define your requests in a constrained extension to `QueryInterfaceRequest`:
Extensions to the `DerivableRequest` protocol can not change the type of requests. This has to be expressed in an extension to `QueryInterfaceRequest`. For example:
```swift
// More requests of Author -------------------------v
// Author requests ~~~~~~~~~~~~~~~~~~~~~~~~~~
extension QueryInterfaceRequest where RowDecoder == Author {
/// Returns a request for all authors with at least one book
func havingBooks() -> QueryInterfaceRequest<Author> {
having(Author.books.isEmpty == false)
// Selects author ids
func id() -> QueryInterfaceRequest<Int64> {
select(Author.Columns.id)
}
}
// IDs of French authors
let ids: [Int64] = try Author.all().filter(country: "France").id().fetchAll(db)
```
Those requests defined on `QueryInterfaceRequest` still compose fluently:
```swift
try dbQueue.read { db in
let sortedFrenchAuthorsHavingBooks = try Author.all()
.filter(country: "France")
.havingBooks() // <-
.orderByName()
.fetchAll(db)
}
```
Finally, when it happens that a request only makes sense when defined on the Record type itself, just go ahead and define a static method or property of your Record type:
```swift
extension MySingletonRecord {
/// The one any only record stored in the database
static let shared = all().limit(1)
}
let singleton = try dbQueue.read { db
try MySingletonRecord.shared.fetchOne(db)
}
```
## Compose Records
We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
@@ -696,7 +787,6 @@ Instead, have a look at [Database Observation]:
[Django]: https://docs.djangoproject.com/en/2.0/topics/db/
[record protocols]: ../README.md#record-protocols-overview
[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns
[Single Responsibility Principle]: https://en.wikipedia.org/wiki/Single_responsibility_principle
[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
[Why Adopt GRDB?]: WhyAdoptGRDB.md
@@ -713,6 +803,8 @@ Instead, have a look at [Database Observation]:
[TransactionObserver]: ../README.md#transactionobserver-protocol
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
[Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details
[Singleton Records]: #singleton-records
[Define Record Requests]: #define-record-requests
[Compose Records]: #compose-records
[How to Design Database Managers]: #how-to-design-database-managers
@@ -727,3 +819,4 @@ Instead, have a look at [Database Observation]:
[Codable Record]: ../README.md#codable-records
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[Combine Support]: Combine.md
[Value]: ../README.md#values
+1 -1
View File
@@ -68,7 +68,7 @@ try dbQueue.read { db in
}
```
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.5/Structs/DatabaseMigrator.html) for more migrator methods.
See the [DatabaseMigrator reference](http://groue.github.io/GRDB.swift/docs/5.6/Structs/DatabaseMigrator.html) for more migrator methods.
## The `eraseDatabaseOnSchemaChange` Option
+240
View File
@@ -0,0 +1,240 @@
Single-Row Tables
=================
Let's talk about database tables that should contain a single row.
Such tables can store configuration values, user preferences, and generally some global application state. They are a suitable alternative to `UserDefaults` in some applications, especially when configuration refers to values found in other database tables, and database integrity is a concern.
This guide helps you implementing a single-row table with GRDB, with recommendations on the database schema, migrations, and the design of a [record] type.
- [The Single-Row Table]
- [The Single-Row Record]
- [Wrap-Up]
## The Single-Row Table
As always with GRDB, everything starts at the level of the database schema. Putting the robust SQLite on our side is always a good idea, because we have to write less code, and this helps shipping less bugs.
We want to instruct SQLite that our table must never contain more than one row. We will never have to wonder what to do if we were unlucky enough to find two rows with conflicting values in this table.
SQLite is not able to guarantee that the table is never empty, so we have to deal with two cases: either the table is empty, either it contains a row.
Those two cases can create a nagging question for the application. By default, inserts fail when the row already exists, and updates fail when the table is empty. In order to avoid those errors, we will have the app perform an insert in case of a failed update (in the [The Single-Row Record] chapter). And we instruct SQLite to just replace the eventual existing row in case of conflicting inserts:
```swift
// CREATE TABLE appConfiguration (
// id INTEGER PRIMARY KEY ON CONFLICT REPLACE CHECK (id = 1),
// flag BOOLEAN NOT NULL,
// ...)
try db.create(table: "appConfiguration") { t in
// Single row guarantee
t.column("id", .integer)
// Have inserts replace the existing row
.primaryKey(onConflict: .replace)
// Make sure the id column is always 1
.check { $0 == 1 }
// The configuration colums
t.column("flag", .boolean).notNull()
// ... other columns
}
```
When you use [migrations], you may wonder if it is a good idea or not to perform an initial insert just after the table is created. Well, this is not recommended:
```swift
// NOT RECOMMENDED
migrator.registerMigration("appConfiguration") { db in
try db.create(table: "appConfiguration") { t in
// Single row guarantee
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
// Define sensible defaults for each column
t.column("flag", .boolean).notNull()
.defaults(to: false)
// ... other columns
}
// Populate the table
try db.execute(sql: "INSERT INTO appConfiguration DEFAULT VALUES")
}
```
It is not a good idea to populate the table in a migration, for two reasons:
1. This is not a hard guarantee that the table will never be empty. As a consequence, this won't prevent your Swift code from dealing with the possibility of a missing row. On top of that, the Swift code that deals with the missing row may not use the same default values as the SQLite schema (a [DRY] violation), with unclear consequences.
2. Migrations that are shipped in the wild should *never* change, because you want to control the state of the databases installed on your users' devices, regardless of the application version they install first, regardless of how many application versions are skipped when they download an upgrade, etc. By inserting an initial row in a migration, you make it difficult for your application to adjust the sensible default values in the future, while keeping a clear idea of the various installation and upgrade scenarios.
The recommended migration creates the table, nothing more:
```swift
// RECOMMENDED
migrator.registerMigration("appConfiguration") { db in
try db.create(table: "appConfiguration") { t in
// Single row guarantee
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
// The configuration colums
t.column("flag", .boolean).notNull()
// ... other columns
}
}
```
## The Single-Row Record
Now that the database schema has been defined, we can define the [record] type that will help the application access the single row:
```swift
struct AppConfiguration: Codable {
// Support for the single row guarantee
private var id = 1
// The configuration properties
var flag: Bool
// ... other properties
}
```
In case the database table would be empty, we need a default configuration:
```swift
extension AppConfiguration {
/// The default configuration
static let `default` = AppConfiguration(flag: false, ...)
}
```
We make our record able to access the database:
```swift
extension AppConfiguration: FetchableRecord, PersistableRecord {
```
We have seen in the [The Single-Row Table] chapter that by default, updates throw an error if the database table is empty. To avoid this error, we instruct GRDB to perform an insert in case of a failed update (see [Persistence Methods] for more information):
```swift
// Customize the default PersistableRecord behavior
func update(_ db: Database, columns: Set<String>) throws {
do {
try performUpdate(db, columns: columns)
} catch PersistenceError.recordNotFound {
// No row was updated: perform an insert
try performInsert(db)
}
}
```
The standard GRDB method `fetchOne` returns an optional which is nil when the database table is empty. As a convenience, let's define a method that returns a non-optional (replacing the missing row with `default`):
```swift
/// Returns the persisted configuration, or the default one if the
/// database table is empty.
static func fetch(_ db: Database) throws -> AppConfiguration {
try fetchOne(db) ?? .default
}
}
```
And that's it! Now we can use our singleton record:
```swift
// READ
let config = try dbQueue.read { db in
try AppConfiguration.fetch(db)
}
if config.flag {
// ...
}
// WRITE
try dbQueue.write { db in
var config = try AppConfiguration.fetch(db)
// Update some config values
try config.updateChanges(db) {
$0.flag = true
}
// Other possible ways to write config:
try config.update(db)
try config.save(db)
try config.insert(db)
}
```
The three `update`, `save` and `insert` methods can be used interchangeably: all three make sure the configuration is stored in the database.
The `updateChanges` method only updates the values changed by its closure argument (and performs an insert if the database table is empty).
See [Persistence Methods] for more information.
## Wrap-Up
We all love to copy and paste, don't we? Just customize the template code below:
```swift
// Table creation
try db.create(table: "appConfiguration") { t in
// Single row guarantee
t.column("id", .integer).primaryKey(onConflict: .replace).check { $0 == 1 }
// The configuration colums
t.column("flag", .boolean).notNull()
// ... other columns
}
```
```swift
//
// AppConfiguration.swift
//
import GRDB
struct AppConfiguration: Codable {
// Support for the single row guarantee
private var id = 1
// The configuration properties
var flag: Bool
// ... other properties
}
extension AppConfiguration {
/// The default configuration
static let `default` = AppConfiguration(flag: false, ...)
}
// Database Access
extension AppConfiguration: FetchableRecord, PersistableRecord {
// Customize the default PersistableRecord behavior
func update(_ db: Database, columns: Set<String>) throws {
do {
try performUpdate(db, columns: columns)
} catch PersistenceError.recordNotFound {
// No row was updated: perform an insert
try performInsert(db)
}
}
/// Returns the persisted configuration, or the default one if the
/// database table is empty.
static func fetch(_ db: Database) throws -> AppConfiguration {
try fetchOne(db) ?? .default
}
}
```
[migrations]: Migrations.md
[record]: ../README.md#records
[The Single-Row Table]: #the-single-row-table
[The Single-Row Record]: #the-single-row-record
[Wrap-Up]: #wrap-up
[DRY]: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself
[Persistence Methods]: ../README.md#persistence-methods
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '5.5.0'
s.version = '5.6.0'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
-10
View File
@@ -829,9 +829,6 @@
56D91AA92205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; };
56D91AAA2205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; };
56D91AAB2205F2F100770D8D /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AA82205F2F000770D8D /* DatabasePromise.swift */; };
56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
56D91AB12205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
56D91AB22205F8AC00770D8D /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
56DAA2D21DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
56DAA2D61DE99DAB006E10C8 /* DatabaseCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */; };
56DAA2DB1DE9C827006E10C8 /* Cursor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56DAA2DA1DE9C827006E10C8 /* Cursor.swift */; };
@@ -953,7 +950,6 @@
AAA4DCB4230F1E0600C74B15 /* HasOneThroughAssociation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56AE64112229A53700AD1B0B /* HasOneThroughAssociation.swift */; };
AAA4DCB5230F1E0600C74B15 /* Statement.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56A238781B9C75030082EB20 /* Statement.swift */; };
AAA4DCB6230F1E0600C74B15 /* ReadWriteBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5659F48F1EA8D964004A4992 /* ReadWriteBox.swift */; };
AAA4DCB7230F1E0600C74B15 /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56D91AAF2205F8AC00770D8D /* SQLQuery.swift */; };
AAA4DCB8230F1E0600C74B15 /* Migration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4391BEB42D500E39BBF /* Migration.swift */; };
AAA4DCB9230F1E0600C74B15 /* Data.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5690C33F1D23E82A00E59934 /* Data.swift */; };
AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5674A6F21F307F600095F066 /* FetchableRecord+Decodable.swift */; };
@@ -1565,7 +1561,6 @@
56D51CFF1EA789FA0074638A /* FetchableRecord+TableRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "FetchableRecord+TableRecord.swift"; sourceTree = "<group>"; };
56D91AA12205E03700770D8D /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
56D91AA82205F2F000770D8D /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = "<group>"; };
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = "<group>"; };
56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCursorTests.swift; sourceTree = "<group>"; };
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Cursor.swift; sourceTree = "<group>"; };
56DE7B101C3D93ED00861EB8 /* StatementArgumentsTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatementArgumentsTests.swift; sourceTree = "<group>"; };
@@ -2042,7 +2037,6 @@
566475CA1D981D5E00FF74B8 /* SQLFunctions.swift */,
566475CB1D981D5E00FF74B8 /* SQLOperators.swift */,
568ECA9E25D7E53E00B71526 /* SQLOrdering.swift */,
56D91AAF2205F8AC00770D8D /* SQLQuery.swift */,
56D91AA12205E03700770D8D /* SQLRelation.swift */,
568ECA8925D7013000B71526 /* SQLSelection.swift */,
568ECB1725D9161500B71526 /* SQLSubquery.swift */,
@@ -2866,7 +2860,6 @@
5698AD1C1DAAD17F0056AF8C /* FTS5Tokenizer.swift in Sources */,
56CEB5171EAA324B00BFAF62 /* FTS3+QueryInterface.swift in Sources */,
5656A8B22295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
56D91AB22205F8AC00770D8D /* SQLQuery.swift in Sources */,
56B964B71DA51D010002DA19 /* FTS5TokenizerDescriptor.swift in Sources */,
5653EB0B20944C7C00F46237 /* Association.swift in Sources */,
564CE59F21B7A8B500652B19 /* RemoveDuplicates.swift in Sources */,
@@ -3070,7 +3063,6 @@
56AE64132229A53700AD1B0B /* HasOneThroughAssociation.swift in Sources */,
56A2388C1B9C75030082EB20 /* Statement.swift in Sources */,
5659F4931EA8D964004A4992 /* ReadWriteBox.swift in Sources */,
56D91AB12205F8AC00770D8D /* SQLQuery.swift in Sources */,
56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */,
5690C3431D23E82A00E59934 /* Data.swift in Sources */,
5674A7001F307F600095F066 /* FetchableRecord+Decodable.swift in Sources */,
@@ -3655,7 +3647,6 @@
AAA4DCB4230F1E0600C74B15 /* HasOneThroughAssociation.swift in Sources */,
AAA4DCB5230F1E0600C74B15 /* Statement.swift in Sources */,
AAA4DCB6230F1E0600C74B15 /* ReadWriteBox.swift in Sources */,
AAA4DCB7230F1E0600C74B15 /* SQLQuery.swift in Sources */,
AAA4DCB8230F1E0600C74B15 /* Migration.swift in Sources */,
AAA4DCB9230F1E0600C74B15 /* Data.swift in Sources */,
AAA4DCBA230F1E0600C74B15 /* FetchableRecord+Decodable.swift in Sources */,
@@ -3946,7 +3937,6 @@
files = (
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
56D91AB02205F8AC00770D8D /* SQLQuery.swift in Sources */,
5616AAF1207CD45E00AC3664 /* RequestProtocols.swift in Sources */,
563B8FC524A1D3B9007A48C9 /* OnDemandFuture.swift in Sources */,
5656A8B02295BFD7001FF3FF /* TableRecord+QueryInterfaceRequest.swift in Sources */,
+18 -2
View File
@@ -108,6 +108,9 @@ public struct Configuration {
/// The function argument is run when an SQLite connection is opened,
/// before the connection is made available for database access methods.
///
/// This method can be called several times. The preparation functions are
/// run in the same order.
///
/// For example:
///
/// var config = Configuration()
@@ -115,8 +118,21 @@ public struct Configuration {
/// try db.execute(sql: "PRAGMA kdf_iter = 10000")
/// }
///
/// This method can be called several times. The setup functions are run in
/// the same order.
/// When you use a `DatabasePool`, preparation functions are called for
/// the writer connection and all reader connections. You can distinguish
/// them by querying `db.configuration.readonly`:
///
/// var config = Configuration()
/// config.prepareDatabase { db in
/// if db.configuration.readonly {
/// // reader connection
/// } else {
/// // writer connection
/// }
/// }
///
/// On newly created databases, `DatabasePool` the WAL mode is activated
/// after the preparation functions have run.
public mutating func prepareDatabase(_ setup: @escaping (Database) throws -> Void) {
setups.append(setup)
}
+148 -21
View File
@@ -9,13 +9,16 @@
//
//===----------------------------------------------------------------------===//
// MARK: - Array, Sequence, Dictionary, Set extensions
// MARK: - RangeReplaceableCollection, Sequence, Dictionary, Set extensions
extension Array {
/// Creates an array containing the elements of a cursor.
extension RangeReplaceableCollection {
/// Creates a collection containing the elements of a cursor.
///
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'bar'")
/// let strings = try Array(cursor) // ["foo", "bar"]
/// // [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor)
///
/// - parameter cursor: The cursor whose elements feed the collection.
@inlinable
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
@@ -23,24 +26,161 @@ extension Array {
append(element)
}
}
/// Creates a collection containing the elements of a cursor.
///
/// // [String]
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Array(cursor, minimumCapacity: 100)
///
/// - parameter cursor: The cursor whose elements feed the collection.
/// - parameter minimumCapacity: Prepares the returned collection to store
/// the specified number of elements.
@inlinable
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
self.init()
reserveCapacity(minimumCapacity)
while let element = try cursor.next() {
append(element)
}
}
}
extension Dictionary {
/// Creates a new dictionary whose keys are the groupings returned by the
/// given closure and whose values are arrays of the elements that returned
/// each key.
public init<C: Cursor>(grouping values: C, by keyForValue: (C.Element) throws -> Key)
///
/// // [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
///
/// - parameter cursor: A cursor of values to group into a dictionary.
/// - parameter keyForValue: A closure that returns a key for each element
/// in the cursor.
public init<C: Cursor>(grouping cursor: C, by keyForValue: (C.Element) throws -> Key)
throws where Value == [C.Element]
{
self.init()
while let value = try values.next() {
while let value = try cursor.next() {
try self[keyForValue(value), default: []].append(value)
}
}
/// Creates a new dictionary whose keys are the groupings returned by the
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// // [Int64: [Player]]
/// let cursor = try Player.fetchCursor(db)
/// let dictionary = try Dictionary(
/// minimumCapacity: 100,
/// grouping: cursor,
/// by: { $0.teamID })
///
/// - parameter minimumCapacity: The minimum number of key-value pairs that
/// the newly created dictionary should be able to store without
/// reallocating its storage buffer.
/// - parameter cursor: A cursor of values to group into a dictionary.
/// - parameter keyForValue: A closure that returns a key for each element
/// in the cursor.
public init<C: Cursor>(minimumCapacity: Int, grouping cursor: C, by keyForValue: (C.Element) throws -> Key)
throws where Value == [C.Element]
{
self.init(minimumCapacity: minimumCapacity)
while let value = try cursor.next() {
try self[keyForValue(value), default: []].append(value)
}
}
/// Creates a new dictionary from the key-value pairs in the given cursor.
///
/// You use this initializer to create a dictionary when you have a cursor
/// of key-value tuples with unique keys. Passing a cursor with duplicate
/// keys to this initializer results in a fatal error.
///
/// // [Int64: Player]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(uniqueKeysWithValues: cursor)
///
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
/// new dictionary. Every key in `keysAndValues` must be unique.
/// - precondition: The cursor must not have duplicate keys.
public init<C: Cursor>(uniqueKeysWithValues keysAndValues: C)
throws where C.Element == (Key, Value)
{
self.init()
while let (key, value) = try keysAndValues.next() {
if updateValue(value, forKey: key) != nil {
fatalError("Duplicate values for key: '\(String(describing: key))'")
}
}
}
/// Creates a new dictionary from the key-value pairs in the given cursor.
///
/// You use this initializer to create a dictionary when you have a cursor
/// of key-value tuples with unique keys. Passing a cursor with duplicate
/// keys to this initializer results in a fatal error.
///
/// // [Int64: Player]
/// let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
/// let playerByID = try Dictionary(
/// minimumCapacity: 100,
/// uniqueKeysWithValues: cursor)
///
/// - parameter minimumCapacity: The minimum number of key-value pairs that
/// the newly created dictionary should be able to store without
/// reallocating its storage buffer.
/// - parameter keysAndValues: A cursor of key-value pairs to use for the
/// new dictionary. Every key in `keysAndValues` must be unique.
/// - precondition: The cursor must not have duplicate keys.
public init<C: Cursor>(minimumCapacity: Int, uniqueKeysWithValues keysAndValues: C)
throws where C.Element == (Key, Value)
{
self.init(minimumCapacity: minimumCapacity)
while let (key, value) = try keysAndValues.next() {
if updateValue(value, forKey: key) != nil {
fatalError("Duplicate values for key: '\(String(describing: key))'")
}
}
}
}
extension Set {
/// Creates a set containing the elements of a cursor.
///
/// // Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor)
///
/// - parameter cursor: A cursor of values to gather into a set.
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
while let element = try cursor.next() {
insert(element)
}
}
/// Creates a set containing the elements of a cursor.
///
/// // Set<String>
/// let cursor = try String.fetchCursor(db, ...)
/// let strings = try Set(cursor, minimumCapacity: 100)
///
/// - parameter cursor: A cursor of values to gather into a set.
/// - parameter minimumCapacity: The minimum number of elements that the
/// newly created set should be able to store without reallocating its
/// storage buffer.
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
self.init(minimumCapacity: minimumCapacity)
while let element = try cursor.next() {
insert(element)
}
}
}
extension Sequence {
/// Returns a cursor over the concatenated results of mapping transform
/// over self.
public func flatMap<SegmentOfResult: Cursor>(
@@ -51,19 +191,6 @@ extension Sequence {
}
}
extension Set {
/// Creates a set containing the elements of a cursor.
///
/// let cursor = try String.fetchCursor(db, sql: "SELECT 'foo' UNION ALL SELECT 'foo'")
/// let strings = try Set(cursor) // ["foo"]
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
while let element = try cursor.next() {
insert(element)
}
}
}
// MARK: - Cursor
/// A type that supplies the values of some external resource, one at a time.
+12
View File
@@ -107,6 +107,18 @@ public final class DatabaseFunction: Hashable {
self.kind = .aggregate { Aggregate() }
}
/// Returns an SQL expression that applies the function.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression {
switch kind {
case .aggregate:
return .function(name, arguments.map(\.sqlExpression))
case .function:
return .aggregate(name, arguments.map(\.sqlExpression))
}
}
/// Calls sqlite3_create_function_v2
/// See https://sqlite.org/c3ref/create_function.html
func install(in db: Database) {
+2 -2
View File
@@ -226,8 +226,8 @@ extension SQLLiteral {
public var arguments: StatementArguments { preconditionFailure() }
}
@available(*, unavailable, renamed: "SQLAssociativeBinaryOperator")
typealias SQLLogicalBinaryOperator = SQLAssociativeBinaryOperator
@available(*, unavailable, renamed: "SQLExpression.AssociativeBinaryOperator")
typealias SQLLogicalBinaryOperator = SQLExpression.AssociativeBinaryOperator
extension SQLRequest {
@available(*, unavailable, renamed: "RowDecoder")
+38 -17
View File
@@ -1,3 +1,5 @@
import Foundation
/// A DatabaseMigrator registers and applies database migrations.
///
/// Migrations are named blocks of SQL statements that are guaranteed to be
@@ -130,27 +132,46 @@ public struct DatabaseMigrator {
return .commit
}
if let lastAppliedIdentifier = migrations.lazy
.map({ $0.identifier })
if let lastAppliedIdentifier = migrations
.map(\.identifier)
.last(where: { appliedIdentifiers.contains($0) })
{
// Database has been partially migrated.
// Some migrations were already applied.
//
// Create a temporary witness database (on disk, just in case
// migrations would involve a lot of data).
var witnessConfiguration = writer.configuration
witnessConfiguration.targetQueue = nil // Avoid deadlocks
witnessConfiguration.label = "GRDB.DatabaseMigrator.temporary"
let witness = try DatabaseQueue(path: "", configuration: witnessConfiguration)
// Let's migrate a temporary database up to the same
// level, and compare the database schemas. If they
// differ, we'll erase the database.
let tmpSchema: SchemaInfo = try {
// Make sure the temporary database is configured
// just as the migrated database
var tmpConfig = writer.configuration
tmpConfig.targetQueue = nil // Avoid deadlocks
tmpConfig.label = "GRDB.DatabaseMigrator.temporary"
// Create the temporary database on disk, just in
// case migrations would involve a lot of data.
//
// SQLite supports temporary on-disk databases, but
// those are not guaranteed to accept the
// preparation functions provided by the user.
//
// See https://github.com/groue/GRDB.swift/issues/931
// for an issue created by such databases.
//
// So let's create a "regular" temporary database:
let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory())
.appendingPathComponent(ProcessInfo().globallyUniqueString)
defer {
try? FileManager().removeItem(at: tmpURL)
}
let tmpDatabase = try DatabaseQueue(path: tmpURL.path, configuration: tmpConfig)
return try tmpDatabase.writeWithoutTransaction { db in
try runMigrations(db, upTo: lastAppliedIdentifier)
return try db.schema()
}
}()
// Grab schema of migrated witness database
let witnessSchema: SchemaInfo = try witness.writeWithoutTransaction { db in
try runMigrations(db, upTo: lastAppliedIdentifier)
return try db.schema()
}
// Erase database if we detect a schema change
if try db.schema() != witnessSchema {
if try db.schema() != tmpSchema {
needsErase = true
return .commit
}
@@ -72,13 +72,12 @@ extension Association {
}
extension Association {
private func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self {
fileprivate func mapDestinationRelation(_ transform: (SQLRelation) -> SQLRelation) -> Self {
.init(sqlAssociation: _sqlAssociation.map(\.destination.relation, transform))
}
}
extension Association {
/// The association key defines how rows fetched from this association
/// should be consumed.
///
@@ -105,6 +104,67 @@ extension Association {
/// }
var key: SQLAssociationKey { _sqlAssociation.destination.key }
/// Creates an association with the given key.
///
/// This new key helps Decodable records decode rows fetched from the
/// resulting association:
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// struct PlayerInfo: FetchableRecord, Decodable {
/// let player: Player
/// let team: Team
///
/// static func all() -> QueryInterfaceRequest<PlayerInfo> {
/// return Player
/// .including(required: Player.team.forKey(CodingKeys.team))
/// .asRequest(of: PlayerInfo.self)
/// }
/// }
///
/// let playerInfos = PlayerInfo.all().fetchAll(db)
/// print(playerInfos.first?.team)
public func forKey(_ codingKey: CodingKey) -> Self {
forKey(codingKey.stringValue)
}
/// Creates an association that allows you to define expressions that target
/// a specific database table.
///
/// In the example below, the "team.color = 'red'" condition in the where
/// clause could be not achieved without table aliases.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.*
/// // JOIN team ON ...
/// // WHERE team.color = 'red'
/// let teamAlias = TableAlias()
/// let request = Player
/// .including(required: Player.team.aliased(teamAlias))
/// .filter(teamAlias[Column("color")] == "red")
///
/// When you give a name to a table alias, you can reliably inject sql
/// snippets in your requests:
///
/// // SELECT player.*, custom.*
/// // JOIN team custom ON ...
/// // WHERE custom.color = 'red'
/// let teamAlias = TableAlias(name: "custom")
/// let request = Player
/// .including(required: Player.team.aliased(teamAlias))
/// .filter(sql: "custom.color = ?", arguments: ["red"])
public func aliased(_ alias: TableAlias) -> Self {
mapDestinationRelation { $0.aliased(alias) }
}
}
extension Association where Self: SelectionRequest {
/// Creates an association which selects *selection*.
///
/// struct Player: TableRecord {
@@ -146,7 +206,9 @@ extension Association {
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> Self {
mapDestinationRelation { $0.annotated { try selection($0).map(\.sqlSelection) } }
}
}
extension Association where Self: FilteredRequest {
/// Creates an association with the provided *predicate promise* added to
/// the eventual set of already applied predicates.
///
@@ -162,7 +224,9 @@ extension Association {
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
mapDestinationRelation { $0.filter { try predicate($0).sqlExpression } }
}
}
extension Association where Self: OrderedRequest {
/// Creates an association with the provided *orderings promise*.
///
/// struct Player: TableRecord {
@@ -229,71 +293,45 @@ extension Association {
public func unordered() -> Self {
mapDestinationRelation { $0.unordered() }
}
/// Creates an association with the given key.
///
/// This new key helps Decodable records decode rows fetched from the
/// resulting association:
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// struct PlayerInfo: FetchableRecord, Decodable {
/// let player: Player
/// let team: Team
///
/// static func all() -> QueryInterfaceRequest<PlayerInfo> {
/// return Player
/// .including(required: Player.team.forKey(CodingKeys.team))
/// .asRequest(of: PlayerInfo.self)
/// }
/// }
///
/// let playerInfos = PlayerInfo.all().fetchAll(db)
/// print(playerInfos.first?.team)
public func forKey(_ codingKey: CodingKey) -> Self {
forKey(codingKey.stringValue)
}
/// Creates an association that allows you to define expressions that target
/// a specific database table.
///
/// In the example below, the "team.color = 'red'" condition in the where
/// clause could be not achieved without table aliases.
///
/// struct Player: TableRecord {
/// static let team = belongsTo(Team.self)
/// }
///
/// // SELECT player.*, team.*
/// // JOIN team ON ...
/// // WHERE team.color = 'red'
/// let teamAlias = TableAlias()
/// let request = Player
/// .including(required: Player.team.aliased(teamAlias))
/// .filter(teamAlias[Column("color")] == "red")
///
/// When you give a name to a table alias, you can reliably inject sql
/// snippets in your requests:
///
/// // SELECT player.*, custom.*
/// // JOIN team custom ON ...
/// // WHERE custom.color = 'red'
/// let teamAlias = TableAlias(name: "custom")
/// let request = Player
/// .including(required: Player.team.aliased(teamAlias))
/// .filter(sql: "custom.color = ?", arguments: ["red"])
public func aliased(_ alias: TableAlias) -> Self {
mapDestinationRelation { $0.aliased(alias) }
}
extension Association where Self: TableRequest {
public var databaseTableName: String {
_sqlAssociation.destination.relation.source.tableName
}
}
// TableRequest
extension Association {
/// :nodoc:
public var databaseTableName: String {
_sqlAssociation.destination.relation.source.tableName
extension Association where Self: AggregatingRequest {
/// Creates an association grouped according to *expressions promise*.
public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> Self {
mapDestinationRelation { $0.group { try expressions($0).map(\.sqlExpression) } }
}
/// Creates an association with the provided *predicate promise* added to
/// the eventual set of already applied predicates.
public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> Self {
mapDestinationRelation { $0.having { try predicate($0).sqlExpression } }
}
}
extension Association where Self: DerivableRequest {
/// Creates an association for returns distinct rows.
public func distinct() -> Self {
mapDestinationRelation { $0.with(\.isDistinct, true) }
}
/// Creates an association that fetches *limit* rows, starting at *offset*.
///
/// Any previous limit is replaced.
public func limit(_ limit: Int, offset: Int? = nil) -> Self {
mapDestinationRelation { $0.with(\.limit, SQLLimit(limit: limit, offset: offset)) }
}
/// Returns an association that embeds the common table expression.
///
/// See `QueryInterfaceRequest.with(_:)` for more information.
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
mapDestinationRelation { $0.with(\.ctes[cte.tableName], cte.cte) }
}
}
@@ -1,25 +1,8 @@
import Foundation
typealias AssociationAggregatePreparation<RowDecoder> =
(inout QueryInterfaceRequest<RowDecoder>)
-> DatabasePromise<SQLExpression>
extension AssociationToMany {
private func makeAggregate(_ expressionPromise: DatabasePromise<SQLExpression>)
-> AssociationAggregate<OriginRowDecoder>
{
AssociationAggregate { request in
let tableAlias = TableAlias()
request = request
.joining(optional: self.aliased(tableAlias))
.groupByPrimaryKey()
return expressionPromise.map { tableAlias[$0] }
}
}
// Convenience
private func makeAggregate(_ expression: SQLExpression) -> AssociationAggregate<OriginRowDecoder> {
makeAggregate(DatabasePromise(value: expression))
AssociationAggregate(preparation: BasePreparation(association: self, expression: expression))
}
/// The number of associated records.
@@ -38,8 +21,8 @@ extension AssociationToMany {
///
/// let teams: [Team] = try Team.having(Team.players.count() > 10).fetchAll(db)
public var count: AssociationAggregate<OriginRowDecoder> {
let expression = SQLExpression.countDistinct(.fastPrimaryKey)
return makeAggregate(expression).forKey("\(key.singularizedName)Count")
makeAggregate(.countDistinct(.fastPrimaryKey))
.forKey("\(key.singularizedName)Count")
}
/// Creates an aggregate that is true if there exists no associated records.
@@ -58,8 +41,8 @@ extension AssociationToMany {
/// let teams: [Team] = try Team.having(!Team.players.isEmpty())
/// let teams: [Team] = try Team.having(Team.players.isEmpty() == false)
public var isEmpty: AssociationAggregate<OriginRowDecoder> {
let expression = SQLExpression.isEmpty(.countDistinct(.fastPrimaryKey))
return makeAggregate(expression).forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
makeAggregate(.isEmpty(.countDistinct(.fastPrimaryKey)))
.forKey("hasNo\(key.singularizedName.uppercasingFirstCharacter)")
}
/// Creates an aggregate which evaluate to the average value of the given
@@ -80,7 +63,7 @@ extension AssociationToMany {
///
/// let teams: [Team] = try Team.having(Team.players.average(Column("score")) > 100).fetchAll(db)
public func average(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.function("AVG", [expression.sqlExpression]))
let aggregate = makeAggregate(.aggregate("AVG", [expression.sqlExpression]))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("average\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
@@ -107,7 +90,7 @@ extension AssociationToMany {
///
/// let teams: [Team] = try Team.having(Team.players.max(Column("score")) < 100).fetchAll(db)
public func max(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.function("MAX", [expression.sqlExpression]))
let aggregate = makeAggregate(.aggregate("MAX", [expression.sqlExpression]))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("max\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
@@ -134,7 +117,7 @@ extension AssociationToMany {
///
/// let teams: [Team] = try Team.having(Team.players.min(Column("score")) > 100).fetchAll(db)
public func min(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.function("MIN", [expression.sqlExpression]))
let aggregate = makeAggregate(.aggregate("MIN", [expression.sqlExpression]))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("min\(name.uppercasingFirstCharacter)\(column.name.uppercasingFirstCharacter)")
@@ -161,7 +144,7 @@ extension AssociationToMany {
///
/// let teams: [Team] = try Team.having(Team.players.sum(Column("score")) > 100).fetchAll(db)
public func sum(_ expression: SQLExpressible) -> AssociationAggregate<OriginRowDecoder> {
let aggregate = makeAggregate(.function("SUM", [expression.sqlExpression]))
let aggregate = makeAggregate(.aggregate("SUM", [expression.sqlExpression]))
if let column = expression as? ColumnExpression {
let name = key.singularizedName
return aggregate.forKey("\(name)\(column.name.uppercasingFirstCharacter)Sum")
@@ -194,9 +177,13 @@ extension AssociationToMany {
/// // Won't compile because Fruit is not Author.
/// let request = Fruit.annotated(with: bookCount)
public struct AssociationAggregate<RowDecoder> {
/// Extend the request with the associated records used to compute the
/// aggregate, and return an expression promise which resolves to the
/// aggregated value.
fileprivate let preparation: AssociationAggregatePreparation<RowDecoder>
/// The SQL name for the value of this aggregate. See forKey(_:).
var key: String? = nil
/// Extends the request with the associated records used to compute the
/// aggregate, and returns the aggregated expression.
///
/// For example:
///
@@ -208,7 +195,7 @@ public struct AssociationAggregate<RowDecoder> {
/// var request = Author.all()
///
/// let aggregate = Author.books.count
/// let expressionPromise = aggregate.prepare(&request)
/// let expression = aggregate.prepare(&request)
///
/// // The request has been extended with associated records:
/// //
@@ -220,17 +207,18 @@ public struct AssociationAggregate<RowDecoder> {
/// // The aggregated value:
/// //
/// // COUNT(DISTINCT book.id)
/// try expressionPromise.resolve(db)
/// expression
///
/// The aggregated value is not right away embedded in the extended request:
/// The aggregated expression is not embedded in the extended request:
///
/// - We don't know yet if the aggregated value will be used in the
/// - We don't know yet if the aggregated expression will be used in the
/// SQL selection, or in the HAVING clause.
/// - It helps implementing aggregate operators such as `&&`, `+`, etc.
let prepare: AssociationAggregatePreparation<RowDecoder>
/// The SQL name for the value of this aggregate. See forKey(_:).
var key: String? = nil
func prepare<Request>(_ request: inout Request) -> SQLExpression
where Request: DerivableRequest, Request.RowDecoder == RowDecoder
{
preparation.prepare(&request)
}
}
extension AssociationAggregate: Refinable {
@@ -265,12 +253,109 @@ extension AssociationAggregate: Refinable {
public func forKey(_ key: CodingKey) -> Self {
forKey(key.stringValue)
}
}
// MARK: - AssociationAggregatePreparation
/// An abstract class that only exists as support for
/// `AssociationAggregate.prepare(_:)`, which needs to prepare both query
/// interface requests and associations through their conformance
/// to `DerivableRequest`:
///
/// aggregate.prepare(&request)
/// aggregate.prepare(&association)
///
/// We could have used a generic closure instead of this class... if only Swift
/// would support generic closures.
private class AssociationAggregatePreparation<RowDecoder> {
func prepare<Request>(_ request: inout Request) -> SQLExpression
where Request: DerivableRequest, Request.RowDecoder == RowDecoder
{
fatalError("subclass must override")
}
}
/// Prepares a request so that it can use association aggregates.
private class BasePreparation<Association: AssociationToMany>:
AssociationAggregatePreparation<Association.OriginRowDecoder> // swiftlint:disable:previous colon
{
private let association: Association
private let expression: SQLExpression
init(association: Association, expression: SQLExpression) {
self.association = association
self.expression = expression
}
override func prepare<Request>(_ request: inout Request) -> SQLExpression
where Request: DerivableRequest, Request.RowDecoder == Association.OriginRowDecoder
{
// The fundamental request that supports association aggregate:
//
// SELECT parent.*
// LEFT JOIN child ON child.parentID = parent.id
// GROUP BY parent.id
let tableAlias = TableAlias()
request = request
.joining(optional: association.aliased(tableAlias))
.groupByPrimaryKey()
// The fundamental request can now be annotated, or filtered in the
// having clause, with the association aggregate expression:
// MIN(child.score), COUNT(DISTINCT child.id), etc.
return expression.qualified(with: tableAlias)
}
}
/// Transforms the expression of an aggregate.
private class MapPreparation<RowDecoder>: AssociationAggregatePreparation<RowDecoder> {
private let base: AssociationAggregatePreparation<RowDecoder>
private let transform: (SQLExpression) -> SQLExpression
init(
base: AssociationAggregatePreparation<RowDecoder>,
transform: @escaping (SQLExpression) -> SQLExpression)
{
self.base = base
self.transform = transform
}
override func prepare<Request>(_ request: inout Request) -> SQLExpression
where Request: DerivableRequest, Request.RowDecoder == RowDecoder
{
transform(base.prepare(&request))
}
}
extension AssociationAggregate {
/// Transforms the expression, and does not preserve key.
fileprivate func map(_ transform: @escaping (SQLExpression) throws -> SQLExpression) -> Self {
AssociationAggregate { request in
self.prepare(&request).map(transform)
}
fileprivate func map(_ transform: @escaping (SQLExpression) -> SQLExpression) -> Self {
AssociationAggregate(preparation: MapPreparation(base: preparation, transform: transform))
}
}
/// Combines the expressions of two aggregates.
private class CombinePreparation<RowDecoder>: AssociationAggregatePreparation<RowDecoder> {
private let lhs: AssociationAggregatePreparation<RowDecoder>
private let rhs: AssociationAggregatePreparation<RowDecoder>
private let combine: (_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression
init(
_ lhs: AssociationAggregatePreparation<RowDecoder>,
_ rhs: AssociationAggregatePreparation<RowDecoder>,
combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression)
{
self.lhs = lhs
self.rhs = rhs
self.combine = combine
}
override func prepare<Request>(_ request: inout Request) -> SQLExpression
where Request: DerivableRequest, Request.RowDecoder == RowDecoder
{
let lhsExpression = lhs.prepare(&request)
let rhsExpression = rhs.prepare(&request)
return combine(lhsExpression, rhsExpression)
}
}
@@ -278,18 +363,10 @@ extension AssociationAggregate: Refinable {
private func combine<RowDecoder>(
_ lhs: AssociationAggregate<RowDecoder>,
_ rhs: AssociationAggregate<RowDecoder>,
with combineExpressions : @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) throws -> SQLExpression)
with combine: @escaping (_ lhs: SQLExpression, _ rhs: SQLExpression) -> SQLExpression)
-> AssociationAggregate<RowDecoder>
{
AssociationAggregate { request in
let lhsPromise = lhs.prepare(&request)
let rhsPromise = rhs.prepare(&request)
return DatabasePromise { db in
try combineExpressions(
lhsPromise.resolve(db),
rhsPromise.resolve(db))
}
}
AssociationAggregate(preparation: CombinePreparation(lhs.preparation, rhs.preparation, combine: combine))
}
// MARK: - Logical Operators (AND, OR, NOT)
@@ -406,83 +406,3 @@ extension CommonTableExpression {
JoinAssociation(to: Destination.relationForAll, condition: .none)
}
}
// MARK: - With
extension QueryInterfaceRequest {
/// Returns a request which embeds the common table expression.
///
/// If a common table expression with the same table name had already been
/// embedded, it is replaced by the new one.
///
/// For example, you can build a request that fetches all chats with their
/// latest message:
///
/// let latestMessageRequest = Message
/// .annotated(with: max(Column("date")))
/// .group(Column("chatID"))
///
/// let latestMessageCTE = CommonTableExpression(
/// named: "latestMessage",
/// request: latestMessageRequest)
///
/// let latestMessage = Chat.association(
/// to: latestMessageCTE,
/// on: { chat, latestMessage in
/// chat[Column("id")] == latestMessage[Column("chatID")]
/// })
///
/// // WITH latestMessage AS
/// // (SELECT *, MAX(date) FROM message GROUP BY chatID)
/// // SELECT chat.*, latestMessage.*
/// // FROM chat
/// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
/// let request = Chat.all()
/// .with(latestMessageCTE)
/// .including(optional: latestMessage)
///
/// - parameter cte: A common table expression.
/// - returns: A request.
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
with(\.query.ctes[cte.tableName], cte.cte)
}
}
extension TableRecord {
/// Returns a request which embeds the common table expression.
///
/// If a common table expression with the same table name had already been
/// embedded, it is replaced by the new one.
///
/// For example, you can build a request that fetches all chats with their
/// latest post:
///
/// let latestMessageRequest = Message
/// .annotated(with: max(Column("date")))
/// .group(Column("chatID"))
///
/// let latestMessageCTE = CommonTableExpression(
/// named: "latestMessage",
/// request: latestMessageRequest)
///
/// let latestMessage = Chat.association(
/// to: latestMessageCTE,
/// on: { chat, latestMessage in
/// chat[Column("id")] == latestMessage[Column("chatID")]
/// })
///
/// // WITH latestMessage AS
/// // (SELECT *, MAX(date) FROM message GROUP BY chatID)
/// // SELECT chat.*, latestMessage.*
/// // FROM chat
/// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
/// let request = Chat
/// .with(latestMessageCTE)
/// .including(optional: latestMessage)
///
/// - parameter cte: A common table expression.
/// - returns: A request.
public static func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> QueryInterfaceRequest<Self> {
all().with(cte)
}
}
@@ -29,24 +29,18 @@
///
/// See https://github.com/groue/GRDB.swift#the-query-interface
public struct QueryInterfaceRequest<RowDecoder> {
var query: SQLQuery
}
extension QueryInterfaceRequest {
init(relation: SQLRelation) {
self.init(query: SQLQuery(relation: relation))
}
var relation: SQLRelation
}
extension QueryInterfaceRequest: Refinable { }
extension QueryInterfaceRequest: FetchRequest {
public var sqlSubquery: SQLSubquery {
.query(query)
.relation(relation)
}
public func fetchCount(_ db: Database) throws -> Int {
try query.fetchCount(db)
try relation.fetchCount(db)
}
public func makePreparedRequest(
@@ -54,13 +48,13 @@ extension QueryInterfaceRequest: FetchRequest {
forSingleResult singleResult: Bool = false)
throws -> PreparedRequest
{
let generator = SQLQueryGenerator(query: query, forSingleResult: singleResult)
let generator = SQLQueryGenerator(relation: relation, forSingleResult: singleResult)
var preparedRequest = try generator.makePreparedRequest(db)
let associations = query.relation.prefetchedAssociations
let associations = relation.prefetchedAssociations
if associations.isEmpty == false {
// Eager loading of prefetched associations
preparedRequest = preparedRequest.with(\.supplementaryFetch) { [query] db, rows in
try prefetch(db, associations: associations, from: query, into: rows)
preparedRequest = preparedRequest.with(\.supplementaryFetch) { [relation] db, rows in
try prefetch(db, associations: associations, from: relation, into: rows)
}
}
return preparedRequest
@@ -83,7 +77,7 @@ extension QueryInterfaceRequest: SelectionRequest {
/// .select { db in [Column("id")] }
/// .select { db in [Column("email")] }
public func select(_ selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
map(\.query) { $0.select { try selection($0).map(\.sqlSelection) } }
map(\.relation) { $0.select { try selection($0).map(\.sqlSelection) } }
}
/// Creates a request which selects *selection*, and fetches values of
@@ -174,7 +168,7 @@ extension QueryInterfaceRequest: SelectionRequest {
/// .select([Column("id"), Column("email")])
/// .annotated(with: { db in [Column("name")] })
public func annotated(with selection: @escaping (Database) throws -> [SQLSelectable]) -> QueryInterfaceRequest {
map(\.query) { $0.annotated { try selection($0).map(\.sqlSelection) } }
map(\.relation) { $0.annotated { try selection($0).map(\.sqlSelection) } }
}
}
@@ -186,7 +180,7 @@ extension QueryInterfaceRequest: FilteredRequest {
/// var request = Player.all()
/// request = request.filter { db in true }
public func filter(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
map(\.query) { $0.filter { try predicate($0).sqlExpression } }
map(\.relation) { $0.filter { try predicate($0).sqlExpression } }
}
}
@@ -205,7 +199,7 @@ extension QueryInterfaceRequest: OrderedRequest {
/// .reversed()
/// .order{ _ in [Column("name")] }
public func order(_ orderings: @escaping (Database) throws -> [SQLOrderingTerm]) -> QueryInterfaceRequest {
map(\.query) { $0.order { try orderings($0).map(\.sqlOrdering) } }
map(\.relation) { $0.order { try orderings($0).map(\.sqlOrdering) } }
}
/// Creates a request that reverses applied orderings.
@@ -220,7 +214,7 @@ extension QueryInterfaceRequest: OrderedRequest {
/// var request = Player.all()
/// request = request.reversed()
public func reversed() -> QueryInterfaceRequest {
map(\.query) { $0.reversed() }
map(\.relation) { $0.reversed() }
}
/// Creates a request without any ordering.
@@ -229,20 +223,20 @@ extension QueryInterfaceRequest: OrderedRequest {
/// var request = Player.all().order(Column("name"))
/// request = request.unordered()
public func unordered() -> QueryInterfaceRequest {
map(\.query) { $0.unordered() }
map(\.relation) { $0.unordered() }
}
}
extension QueryInterfaceRequest: AggregatingRequest {
/// Creates a request grouped according to *expressions promise*.
public func group(_ expressions: @escaping (Database) throws -> [SQLExpressible]) -> QueryInterfaceRequest {
map(\.query) { $0.group { try expressions($0).map(\.sqlExpression) } }
map(\.relation) { $0.group { try expressions($0).map(\.sqlExpression) } }
}
/// Creates a request with the provided *predicate promise* added to the
/// eventual set of already applied predicates.
public func having(_ predicate: @escaping (Database) throws -> SQLExpressible) -> QueryInterfaceRequest {
map(\.query) { $0.having { try predicate($0).sqlExpression } }
map(\.relation) { $0.having { try predicate($0).sqlExpression } }
}
}
@@ -250,27 +244,27 @@ extension QueryInterfaceRequest: AggregatingRequest {
extension QueryInterfaceRequest: _JoinableRequest {
/// :nodoc:
public func _including(all association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._including(all: association) }
map(\.relation) { $0._including(all: association) }
}
/// :nodoc:
public func _including(optional association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._including(optional: association) }
map(\.relation) { $0._including(optional: association) }
}
/// :nodoc:
public func _including(required association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._including(required: association) }
map(\.relation) { $0._including(required: association) }
}
/// :nodoc:
public func _joining(optional association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._joining(optional: association) }
map(\.relation) { $0._joining(optional: association) }
}
/// :nodoc:
public func _joining(required association: _SQLAssociation) -> QueryInterfaceRequest {
map(\.query) { $0._joining(required: association) }
map(\.relation) { $0._joining(required: association) }
}
}
@@ -279,7 +273,7 @@ extension QueryInterfaceRequest: JoinableRequest { }
extension QueryInterfaceRequest: TableRequest {
/// :nodoc:
public var databaseTableName: String {
query.relation.source.tableName
relation.source.tableName
}
/// Creates a request that allows you to define expressions that target
@@ -300,37 +294,25 @@ extension QueryInterfaceRequest: TableRequest {
/// .aliased(playerAlias)
/// .including(required: Player.team.filter(Column("avgScore") < playerAlias[Column("score")])
public func aliased(_ alias: TableAlias) -> QueryInterfaceRequest {
map(\.query) { $0.aliased(alias) }
map(\.relation) { $0.aliased(alias) }
}
}
extension QueryInterfaceRequest: DerivableRequest where RowDecoder: TableRecord { }
extension QueryInterfaceRequest: DerivableRequest {
public func distinct() -> QueryInterfaceRequest {
with(\.relation.isDistinct, true)
}
public func limit(_ limit: Int, offset: Int?) -> QueryInterfaceRequest {
with(\.relation.limit, SQLLimit(limit: limit, offset: offset))
}
public func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self {
with(\.relation.ctes[cte.tableName], cte.cte)
}
}
extension QueryInterfaceRequest {
/// Creates a request which returns distinct rows.
///
/// // SELECT DISTINCT * FROM player
/// var request = Player.all()
/// request = request.distinct()
///
/// // SELECT DISTINCT name FROM player
/// var request = Player.select(Column("name"))
/// request = request.distinct()
public func distinct() -> QueryInterfaceRequest {
map(\.query) { $0.distinct() }
}
/// Creates a request which fetches *limit* rows, starting at *offset*.
///
/// // SELECT * FROM player LIMIT 1
/// var request = Player.all()
/// request = request.limit(1)
///
/// Any previous limit is replaced.
public func limit(_ limit: Int, offset: Int? = nil) -> QueryInterfaceRequest {
map(\.query) { $0.limit(limit, offset: offset) }
}
/// Creates a request bound to type RowDecoder.
///
/// The returned request can fetch if the type RowDecoder is fetchable (Row,
@@ -345,58 +327,7 @@ extension QueryInterfaceRequest {
/// - parameter type: The fetched type RowDecoder
/// - returns: A request bound to type RowDecoder.
public func asRequest<RowDecoder>(of type: RowDecoder.Type) -> QueryInterfaceRequest<RowDecoder> {
QueryInterfaceRequest<RowDecoder>(query: query)
}
}
// MARK: - Aggregates
extension QueryInterfaceRequest {
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
var request = self
let expressionPromise = aggregate.prepare(&request)
if let key = aggregate.key {
return request.annotated(with: { db in try [expressionPromise.resolve(db).forKey(key)] })
} else {
return request.annotated(with: { db in try [expressionPromise.resolve(db)] })
}
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: Player.books.count)
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> QueryInterfaceRequest {
annotated(with: aggregates)
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: [Player.books.count])
public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> QueryInterfaceRequest {
aggregates.reduce(self) { request, aggregate in
request.annotated(with: aggregate)
}
}
/// Creates a request which appends the provided aggregate *predicate* to
/// the eventual set of already applied predicates.
///
/// // SELECT player.*
/// // FROM player LEFT JOIN book ...
/// // HAVING COUNT(DISTINCT book.id) = 0
/// var request = Player.all()
/// request = request.having(Player.books.isEmpty)
public func having(_ predicate: AssociationAggregate<RowDecoder>) -> QueryInterfaceRequest {
var request = self
let expressionPromise = predicate.prepare(&request)
return request.having(expressionPromise.resolve)
QueryInterfaceRequest<RowDecoder>(relation: relation)
}
}
@@ -410,7 +341,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
/// - throws: A DatabaseError is thrown whenever an SQLite error occurs.
@discardableResult
public func deleteAll(_ db: Database) throws -> Int {
try SQLQueryGenerator(query: query).makeDeleteStatement(db).execute()
try SQLQueryGenerator(relation: relation).makeDeleteStatement(db).execute()
return db.changesCount
}
}
@@ -440,7 +371,7 @@ extension QueryInterfaceRequest where RowDecoder: MutablePersistableRecord {
_ assignments: [ColumnAssignment]) throws -> Int
{
let conflictResolution = conflictResolution ?? RowDecoder.persistenceConflictPolicy.conflictResolutionForUpdate
guard let updateStatement = try SQLQueryGenerator(query: query).makeUpdateStatement(
guard let updateStatement = try SQLQueryGenerator(relation: relation).makeUpdateStatement(
db,
conflictResolution: conflictResolution,
assignments: assignments) else
@@ -582,7 +513,7 @@ public func /= (column: ColumnExpression, value: SQLExpressible) -> ColumnAssign
private func prefetch(
_ db: Database,
associations: [_SQLAssociation],
from originQuery: SQLQuery,
from originRelation: SQLRelation,
into originRows: [Row]) throws
{
guard let firstOriginRow = originRows.first else {
@@ -598,7 +529,7 @@ private func prefetch(
fatalError("Not implemented: prefetch association without any foreign key")
case let .foreignKey(pivotForeignKey):
let originTable = originQuery.relation.source.tableName
let originTable = originRelation.source.tableName
let pivotMapping = try pivotForeignKey.joinMapping(db, from: originTable)
let pivotColumns = pivotMapping.map(\.right)
let leftColumns = pivotMapping.map(\.left)
@@ -647,17 +578,16 @@ private func prefetch(
// FROM country
// JOIN passport ON passport.countryCode = country.code
// AND (passport.a, passport.b) IN grdb_base
let originQuery = originQuery.map(\.relation) { baseRelation in
// Ordering and including(all:) children are
// useless, and we only need pivoting columns:
baseRelation
.unordered()
.removingChildrenForPrefetchedAssociations()
.selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection })
}
//
// In the CTE, ordering and including(all:) children are
// useless, and we only need to select pivot columns:
let originRelation = originRelation
.unordered()
.removingChildrenForPrefetchedAssociations()
.selectOnly(leftColumns.map { SQLExpression.column($0).sqlSelection })
let originCTE = CommonTableExpression(
named: "grdb_base",
request: SQLSubquery.query(originQuery))
request: SQLSubquery.relation(originRelation))
let pivotRowValue = SQLExpression.rowValue(pivotColumns.map(SQLExpression.column))!
let pivotFilter = originCTE.contains(pivotRowValue)
@@ -785,9 +715,7 @@ throws -> DatabaseRegion
.map(\.pivot.relation) { $0.filter(pivotFilter) }
.destinationRelation()
let prefetchQuery = SQLQuery(relation: prefetchRelation)
return try SQLQueryGenerator(query: prefetchQuery)
return try SQLQueryGenerator(relation: prefetchRelation)
.makeSelectStatement(db)
.databaseRegion // contains region of nested associations
}
@@ -590,4 +590,118 @@ extension JoinableRequest {
// MARK: - DerivableRequest
/// The base protocol for all requests that can be refined.
public protocol DerivableRequest: FilteredRequest, JoinableRequest, OrderedRequest, SelectionRequest, TableRequest { }
public protocol DerivableRequest: AggregatingRequest, FilteredRequest,
JoinableRequest, OrderedRequest,
SelectionRequest, TableRequest
{
/// Creates a request which returns distinct rows.
///
/// // SELECT DISTINCT * FROM player
/// var request = Player.all()
/// request = request.distinct()
///
/// // SELECT DISTINCT name FROM player
/// var request = Player.select(Column("name"))
/// request = request.distinct()
func distinct() -> Self
/// Creates a request which fetches *limit* rows, starting at *offset*.
///
/// // SELECT * FROM player LIMIT 10 OFFSET 20
/// var request = Player.all()
/// request = request.limit(10, offset: 20)
///
/// Any previous limit is replaced.
func limit(_ limit: Int, offset: Int?) -> Self
/// Returns a request which embeds the common table expression.
///
/// If a common table expression with the same table name had already been
/// embedded, it is replaced by the new one.
///
/// For example, you can build a request that fetches all chats with their
/// latest message:
///
/// let latestMessageRequest = Message
/// .annotated(with: max(Column("date")))
/// .group(Column("chatID"))
///
/// let latestMessageCTE = CommonTableExpression(
/// named: "latestMessage",
/// request: latestMessageRequest)
///
/// let latestMessage = Chat.association(
/// to: latestMessageCTE,
/// on: { chat, latestMessage in
/// chat[Column("id")] == latestMessage[Column("chatID")]
/// })
///
/// // WITH latestMessage AS
/// // (SELECT *, MAX(date) FROM message GROUP BY chatID)
/// // SELECT chat.*, latestMessage.*
/// // FROM chat
/// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
/// let request = Chat.all()
/// .with(latestMessageCTE)
/// .including(optional: latestMessage)
func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> Self
}
extension DerivableRequest {
/// Creates a request which fetches *limit* rows.
///
/// // SELECT * FROM player LIMIT 1
/// var request = Player.all()
/// request = request.limit(1)
///
/// Any previous limit is replaced.
public func limit(_ limit: Int) -> Self {
self.limit(limit, offset: nil)
}
private func annotated(with aggregate: AssociationAggregate<RowDecoder>) -> Self {
var request = self
let expression = aggregate.prepare(&request)
if let key = aggregate.key {
return request.annotated(with: expression.forKey(key))
} else {
return request.annotated(with: expression)
}
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: Player.books.count)
public func annotated(with aggregates: AssociationAggregate<RowDecoder>...) -> Self {
annotated(with: aggregates)
}
/// Creates a request which appends *aggregates* to the current selection.
///
/// // SELECT player.*, COUNT(DISTINCT book.id) AS bookCount
/// // FROM player LEFT JOIN book ...
/// var request = Player.all()
/// request = request.annotated(with: [Player.books.count])
public func annotated(with aggregates: [AssociationAggregate<RowDecoder>]) -> Self {
aggregates.reduce(self) { request, aggregate in
request.annotated(with: aggregate)
}
}
/// Creates a request which appends the provided aggregate *predicate* to
/// the eventual set of already applied predicates.
///
/// // SELECT player.*
/// // FROM player LEFT JOIN book ...
/// // HAVING COUNT(DISTINCT book.id) = 0
/// var request = Player.all()
/// request = request.having(Player.books.isEmpty)
public func having(_ predicate: AssociationAggregate<RowDecoder>) -> Self {
var request = self
let expression = predicate.prepare(&request)
return request.having(expression)
}
}
File diff suppressed because it is too large. Load diff
+6 -17
View File
@@ -1,15 +1,3 @@
// MARK: - Custom Functions
extension DatabaseFunction {
/// Returns an SQL expression that applies the function.
///
/// See https://github.com/groue/GRDB.swift/#sql-functions
public func callAsFunction(_ arguments: SQLExpressible...) -> SQLExpression {
.function(name, arguments.map(\.sqlExpression))
}
}
// MARK: - ABS(...)
/// Returns an expression that evaluates the `ABS` SQL function.
@@ -28,18 +16,19 @@ public func abs(_ value: SQLSpecificExpressible) -> SQLExpression {
/// // AVG(length)
/// average(Column("length"))
public func average(_ value: SQLSpecificExpressible) -> SQLExpression {
.function("AVG", [value.sqlExpression])
.aggregate("AVG", [value.sqlExpression])
}
// MARK: - COUNT(...)
// TODO: deprecate, replace with count(expression)
/// Returns an expression that evaluates the `COUNT` SQL function.
///
/// // COUNT(email)
/// count(Column("email"))
public func count(_ counted: SQLSelectable) -> SQLExpression {
.count(counted.sqlSelection)
counted.sqlSelection.countExpression
}
@@ -83,7 +72,7 @@ public func length(_ value: SQLSpecificExpressible) -> SQLExpression {
/// // MAX(score)
/// max(Column("score"))
public func max(_ value: SQLSpecificExpressible) -> SQLExpression {
.function("MAX", [value.sqlExpression])
.aggregate("MAX", [value.sqlExpression])
}
@@ -94,7 +83,7 @@ public func max(_ value: SQLSpecificExpressible) -> SQLExpression {
/// // MIN(score)
/// min(Column("score"))
public func min(_ value: SQLSpecificExpressible) -> SQLExpression {
.function("MIN", [value.sqlExpression])
.aggregate("MIN", [value.sqlExpression])
}
@@ -105,7 +94,7 @@ public func min(_ value: SQLSpecificExpressible) -> SQLExpression {
/// // SUM(amount)
/// sum(Column("amount"))
public func sum(_ value: SQLSpecificExpressible) -> SQLExpression {
.function("SUM", [value.sqlExpression])
.aggregate("SUM", [value.sqlExpression])
}
-164
View File
@@ -1,164 +0,0 @@
/// SQLQuery is a representation of an SQL query.
///
/// See SQLQueryGenerator for actual SQL generation.
struct SQLQuery {
var relation: SQLRelation
var isDistinct: Bool = false
var groupPromise: DatabasePromise<[SQLExpression]>?
var havingExpressionPromise: DatabasePromise<SQLExpression?> = DatabasePromise(value: nil)
var limit: SQLLimit?
var ctes: OrderedDictionary<String, SQLCTE> = [:]
}
extension SQLQuery: Refinable {
func distinct() -> Self {
with(\.isDistinct, true)
}
func limit(_ limit: Int, offset: Int? = nil) -> Self {
with(\.limit, SQLLimit(limit: limit, offset: offset))
}
func aliased(_ alias: TableAlias) -> Self {
map(\.relation) { $0.aliased(alias) }
}
}
extension SQLQuery {
func select(_ selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
map(\.relation) { $0.select(selection) }
}
// Convenience
func select(_ expressions: SQLExpression...) -> Self {
select { _ in expressions.map { .expression($0) } }
}
func annotated(with selection: @escaping (Database) throws -> [SQLSelection]) -> Self {
map(\.relation) { $0.annotated(with: selection) }
}
}
extension SQLQuery {
func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
map(\.relation) { $0.filter(predicate) }
}
}
extension SQLQuery {
func order(_ orderings: @escaping (Database) throws -> [SQLOrdering]) -> Self {
map(\.relation) { $0.order(orderings) }
}
func reversed() -> Self {
map(\.relation) { $0.reversed() }
}
func unordered() -> Self {
map(\.relation) { $0.unordered() }
}
}
extension SQLQuery {
func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
with(\.groupPromise, DatabasePromise(expressions))
}
func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
map(\.havingExpressionPromise) { promise in
DatabasePromise { db in
if let filter = try promise.resolve(db) {
return try filter && predicate(db)
} else {
return try predicate(db)
}
}
}
}
}
extension SQLQuery{
func _including(all association: _SQLAssociation) -> Self {
map(\.relation) { $0._including(all: association) }
}
func _including(optional association: _SQLAssociation) -> Self {
map(\.relation) { $0._including(optional: association) }
}
func _including(required association: _SQLAssociation) -> Self {
map(\.relation) { $0._including(required: association) }
}
func _joining(optional association: _SQLAssociation) -> Self {
map(\.relation) { $0._joining(optional: association) }
}
func _joining(required association: _SQLAssociation) -> Self {
map(\.relation) { $0._joining(required: association) }
}
}
extension SQLQuery {
func fetchCount(_ db: Database) throws -> Int {
guard groupPromise == nil && limit == nil && ctes.isEmpty else {
// SELECT ... GROUP BY ...
// SELECT ... LIMIT ...
// WITH ... SELECT ...
return try fetchTrivialCount(db)
}
if relation.children.contains(where: { $0.value.impactsParentCount }) { // TODO: not tested
// SELECT ... FROM ... JOIN ...
return try fetchTrivialCount(db)
}
let selection = try relation.selectionPromise.resolve(db)
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
if selection.count == 1 {
guard let count = selection[0].count(distinct: isDistinct) else {
return try fetchTrivialCount(db)
}
var countQuery = self.unordered()
countQuery.isDistinct = false
switch count {
case .all:
countQuery = countQuery.select(.count(.allColumns))
case .distinct(let expression):
countQuery = countQuery.select(.countDistinct(expression))
}
return try QueryInterfaceRequest(query: countQuery).fetchOne(db)!
} else {
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
guard !isDistinct else {
return try fetchTrivialCount(db)
}
// SELECT expr1, expr2, ... FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
let countQuery = unordered().select(SQLExpression.count(.allColumns))
return try QueryInterfaceRequest(query: countQuery).fetchOne(db)!
}
}
// SELECT COUNT(*) FROM (self)
func fetchTrivialCount(_ db: Database) throws -> Int {
let countRequest: SQLRequest<Int> = "SELECT COUNT(*) FROM (\(SQLSubquery.query(unordered())))"
return try countRequest.fetchOne(db)!
}
}
struct SQLLimit {
let limit: Int
let offset: Int?
var sql: String {
if let offset = offset {
return "\(limit) OFFSET \(offset)"
} else {
return "\(limit)"
}
}
}
+210 -46
View File
@@ -2,23 +2,20 @@
/// terminology](https://en.wikipedia.org/wiki/Relational_database#Terminology),
/// is "a set of tuples sharing the same attributes; a set of columns and rows."
///
/// SQLRelation is defined with a selection, a source table of query, and an
/// eventual filter and ordering.
///
/// SELECT ... FROM ... WHERE ... ORDER BY ...
/// | | | |
/// | | | • ordering
/// | | • filter
/// | • source
/// • selection
///
/// Other SQL clauses such as GROUP BY, LIMIT are defined one level up, in the
/// `SQLQuery` type.
/// WITH ... -- ctes
/// SELECT ... -- selectionPromise
/// FROM ... -- source
/// JOIN ... -- children
/// WHERE ... -- filterPromise
/// GROUP BY ... -- groupPromise
/// HAVING ... -- havingExpressionPromise
/// ORDER BY ... -- ordering
/// LIMIT ... -- limit
///
/// ## Promises
///
/// Selection, filter, and ordering are "promises" which are resolved when a
/// database connection is available. This is how we can implement requests such
/// Most relation elements are "promises" which are resolved when a database
/// connection is available. This is how we can implement requests such
/// as `Record.filter(key: 1)` or `Record.orderByPrimaryKey()`: both need a
/// database connection in order to introspect the primary key. For example:
///
@@ -29,7 +26,7 @@
///
/// ## Children
///
/// Relations may also have children. A child is a link to another relation, and
/// Relations have children. A child is a link to another relation, and
/// provide support for joins and prefetched relations.
///
/// Relations and their children constitute a tree of relations, which the user
@@ -123,6 +120,27 @@ struct SQLRelation {
}
}
init(kind: SQLRelation.Child.Kind, condition: SQLAssociationCondition, relation: SQLRelation) {
switch kind {
case .oneOptional, .oneRequired, .bridge:
if relation.isDistinct {
fatalError("Can't join an association that selects DISTINCT rows")
}
if relation.groupPromise != nil || relation.havingExpressionPromise != nil {
fatalError("Not implemented: join an association with a GROUP BY clause")
}
if relation.limit != nil {
fatalError("Can't join an association with a LIMIT clause")
}
case .all:
break
}
self.kind = kind
self.condition = condition
self.relation = relation
}
fileprivate func makeAssociationForKey(_ key: String) -> _SQLAssociation {
let key = SQLAssociationKey.fixed(key)
@@ -143,30 +161,18 @@ struct SQLRelation {
}
var source: SQLSource
var selectionPromise: DatabasePromise<[SQLSelection]> = DatabasePromise(value: [])
var filterPromise: DatabasePromise<SQLExpression?> = DatabasePromise(value: nil)
var selectionPromise: DatabasePromise<[SQLSelection]>
var filterPromise: DatabasePromise<SQLExpression>?
var ordering: SQLRelation.Ordering = SQLRelation.Ordering()
var ctes: OrderedDictionary<String, SQLCTE> = [:] // See also `allCTEs`
var children: OrderedDictionary<String, Child> = [:]
/// All prefetched associations (`including(all:)`), recursively
var prefetchedAssociations: [_SQLAssociation] {
children.flatMap { key, child -> [_SQLAssociation] in
switch child.kind {
case .all:
return [child.makeAssociationForKey(key)]
case .oneOptional, .oneRequired, .bridge:
return child.relation.prefetchedAssociations.map { association in
// Remove redundant pivot child
let pivotKey = association.pivot.keyName
let child = child.map(\.relation) { relation in
assert(relation.children[pivotKey] != nil)
return relation.removingChild(forKey: pivotKey)
}
return association.through(child.makeAssociationForKey(key))
}
}
}
}
// Properties below MUST NOT be used when joining to-one associations.
// This is guaranteed by Child.init().
var isDistinct = false
var groupPromise: DatabasePromise<[SQLExpression]>?
var havingExpressionPromise: DatabasePromise<SQLExpression>?
var limit: SQLLimit?
}
extension SQLRelation {
@@ -192,10 +198,17 @@ extension SQLRelation: Refinable {
select { _ in selection }
}
/// Removes all selections from chidren
// Convenience
func select(_ expressions: SQLExpression...) -> Self {
select { _ in expressions.map { .expression($0) } }
}
/// Sets the selection, removes all selections from chidren, and clears the
/// `isDistinct` flag.
func selectOnly(_ selection: [SQLSelection]) -> Self {
self
.select(selection)
.with(\.isDistinct, false)
.map(\.children) { children in
children.mapValues { child in
child.map(\.relation) { $0.selectOnly([]) }
@@ -219,7 +232,7 @@ extension SQLRelation: Refinable {
func filter(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
map(\.filterPromise) { promise in
DatabasePromise { db in
if let filter = try promise.resolve(db) {
if let filter = try promise?.resolve(db) {
return try filter && predicate(db)
} else {
return try predicate(db)
@@ -251,12 +264,60 @@ extension SQLRelation: Refinable {
}
}
func group(_ expressions: @escaping (Database) throws -> [SQLExpression]) -> Self {
with(\.groupPromise, DatabasePromise(expressions))
}
func having(_ predicate: @escaping (Database) throws -> SQLExpression) -> Self {
map(\.havingExpressionPromise) { promise in
DatabasePromise { db in
if let filter = try promise?.resolve(db) {
return try filter && predicate(db)
} else {
return try predicate(db)
}
}
}
}
func aliased(_ alias: TableAlias) -> Self {
map(\.source) { $0.aliased(alias) }
}
}
extension SQLRelation {
/// All prefetched associations (`including(all:)`), recursively
var prefetchedAssociations: [_SQLAssociation] {
children.flatMap { key, child -> [_SQLAssociation] in
switch child.kind {
case .all:
return [child.makeAssociationForKey(key)]
case .oneOptional, .oneRequired, .bridge:
return child.relation.prefetchedAssociations.map { association in
// Remove redundant pivot child
let pivotKey = association.pivot.keyName
let child = child.map(\.relation) { relation in
assert(relation.children[pivotKey] != nil)
return relation.removingChild(forKey: pivotKey)
}
return association.through(child.makeAssociationForKey(key))
}
}
}
}
/// All common table expressions, including those of joined children.
var allCTEs: OrderedDictionary<String, SQLCTE> {
children.values.reduce(into: ctes) { (ctes, child) in
switch child.kind {
case .all, .bridge:
break
case .oneOptional, .oneRequired:
ctes.merge(child.relation.allCTEs, uniquingKeysWith: { (_, new) in new })
}
}
}
/// Returns a relation extended with an association.
///
/// This method provides support for public joining methods such
@@ -466,6 +527,72 @@ extension SQLRelation {
}
}
extension SQLRelation {
func fetchCount(_ db: Database) throws -> Int {
guard groupPromise == nil && limit == nil && ctes.isEmpty else {
// SELECT ... GROUP BY ...
// SELECT ... LIMIT ...
// WITH ... SELECT ...
return try fetchTrivialCount(db)
}
if children.contains(where: { $0.value.impactsParentCount }) { // TODO: not tested
// SELECT ... FROM ... JOIN ...
return try fetchTrivialCount(db)
}
let selection = try selectionPromise.resolve(db)
GRDBPrecondition(!selection.isEmpty, "Can't generate SQL with empty selection")
if selection.count == 1 {
guard let count = selection[0].count(distinct: isDistinct) else {
return try fetchTrivialCount(db)
}
var countRelation = self.unordered()
countRelation.isDistinct = false
switch count {
case .all:
countRelation = countRelation.select(.countAll)
case .distinct(let expression):
countRelation = countRelation.select(.countDistinct(expression))
}
return try QueryInterfaceRequest(relation: countRelation).fetchOne(db)!
} else {
// SELECT [DISTINCT] expr1, expr2, ... FROM tableName ...
guard !isDistinct else {
return try fetchTrivialCount(db)
}
// SELECT expr1, expr2, ... FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
let countRelation = unordered().select(.countAll)
return try QueryInterfaceRequest(relation: countRelation).fetchOne(db)!
}
}
// SELECT COUNT(*) FROM (self)
private func fetchTrivialCount(_ db: Database) throws -> Int {
let countRequest: SQLRequest<Int> = "SELECT COUNT(*) FROM (\(SQLSubquery.relation(unordered())))"
return try countRequest.fetchOne(db)!
}
}
// MARK: - SQLLimit
struct SQLLimit {
let limit: Int
let offset: Int?
var sql: String {
if let offset = offset {
return "\(limit) OFFSET \(offset)"
} else {
return "\(limit)"
}
}
}
// MARK: - SQLSource
struct SQLSource {
@@ -839,19 +966,26 @@ extension PersistenceContainer: ColumnAddressable {
extension SQLRelation {
/// Returns nil if relations can't be merged (conflict in source, joins...)
func merged(with other: SQLRelation) -> Self? {
// Source
guard let mergedSource = source.merged(with: other.source) else {
// can't merge
return nil
}
let mergedFilterPromise = DatabasePromise<SQLExpression?> { db in
switch try (self.filterPromise.resolve(db), other.filterPromise.resolve(db)) {
case let (lhs?, rhs?): return lhs && rhs
case let (nil, expr?), let (expr?, nil): return expr
case (nil, nil): return nil
// Filter: merge with AND
let mergedFilterPromise: DatabasePromise<SQLExpression>?
switch (filterPromise, other.filterPromise) {
case let (lhs?, rhs?):
mergedFilterPromise = DatabasePromise {
try lhs.resolve($0) && rhs.resolve($0)
}
case let (nil, promise?), let (promise?, nil):
mergedFilterPromise = promise
case (nil, nil):
mergedFilterPromise = nil
}
// Children: merge recursively
var mergedChildren: OrderedDictionary<String, SQLRelation.Child> = [:]
for (key, child) in children {
if let otherChild = other.children[key] {
@@ -868,7 +1002,7 @@ extension SQLRelation {
mergedChildren.appendValue(child, forKey: key)
}
// replace selection unless empty
// Selection: replace unless empty
let mergedSelectionPromise = DatabasePromise { db -> [SQLSelection] in
let otherSelection = try other.selectionPromise.resolve(db)
if otherSelection.isEmpty {
@@ -878,15 +1012,45 @@ extension SQLRelation {
}
}
// replace ordering unless empty
// Ordering: prefer other
let mergedOrdering = other.ordering.isEmpty ? ordering : other.ordering
// Distinct
let mergedDistinct = isDistinct || other.isDistinct
// Grouping: prefer other
let mergedGroupPromise = other.groupPromise ?? groupPromise
// Having: merge with AND
let mergedHavingExpressionPromise: DatabasePromise<SQLExpression>?
switch (havingExpressionPromise, other.havingExpressionPromise) {
case let (lhs?, rhs?):
mergedHavingExpressionPromise = DatabasePromise {
try lhs.resolve($0) && rhs.resolve($0)
}
case let (nil, promise?), let (promise?, nil):
mergedHavingExpressionPromise = promise
case (nil, nil):
mergedHavingExpressionPromise = nil
}
// Limit: prefer other
let mergedLimit = other.limit ?? limit
// CTEs: merge & prefer other
let mergedCTEs = ctes.merging(other.ctes, uniquingKeysWith: { (_, other) in other })
return SQLRelation(
source: mergedSource,
selectionPromise: mergedSelectionPromise,
filterPromise: mergedFilterPromise,
ordering: mergedOrdering,
children: mergedChildren)
ctes: mergedCTEs,
children: mergedChildren,
isDistinct: mergedDistinct,
groupPromise: mergedGroupPromise,
havingExpressionPromise: mergedHavingExpressionPromise,
limit: mergedLimit)
}
}
+41 -23
View File
@@ -3,15 +3,12 @@
public struct SQLSelection {
private var impl: Impl
/// The private implementation of the public `SQLSelection`.
private enum Impl {
/// All columns
///
/// SELECT *
/// All columns: `*`
case allColumns
/// All columns from a table
///
/// SELECT player.*
/// All columns, qualified: `player.*`
case qualifiedAllColumns(TableAlias)
// As long as the CTE is embedded here, the following request will fail
@@ -28,48 +25,55 @@ public struct SQLSelection {
// - prefer `annotated(with:)` when she wants to extend the selection.
//
// TODO: Make `cteRequestOrAssociation.select(AllColumns())` possible.
/// All columns from a common table expression
/// All columns of a common table expression
case allCTEColumns(SQLCTE)
/// All columns of a common table expression, qualified
case qualifiedAllCTEColumns(SQLCTE, TableAlias)
/// An expression
///
/// SELECT id
/// SELECT LENGTH(name)
case expression(SQLExpression)
/// An aliased expression
///
/// SELECT score + bonud AS totalScore
/// <expression> AS name
case aliasedExpression(SQLExpression, String)
/// A literal SQL selection
case literal(SQLLiteral)
}
/// All columns: `*`
static let allColumns = SQLSelection(impl: .allColumns)
/// All columns, qualified: `player.*`
static func qualifiedAllColumns(_ alias: TableAlias) -> Self {
self.init(impl: .qualifiedAllColumns(alias))
}
/// All columns of a common table expression
static func allCTEColumns(_ cte: SQLCTE) -> Self {
self.init(impl: .allCTEColumns(cte))
}
/// All columns of a common table expression, qualified
static func qualifiedAllCTEColumns(_ cte: SQLCTE, _ alias: TableAlias) -> Self {
self.init(impl: .qualifiedAllCTEColumns(cte, alias))
}
/// An expression
static func expression(_ expression: SQLExpression) -> Self {
self.init(impl: .expression(expression))
}
/// An aliased expression
///
/// <expression> AS name
static func aliasedExpression(_ expression: SQLExpression, _ name: String) -> Self {
self.init(impl: .aliasedExpression(expression, name))
}
/// A literal SQL selection
static func literal(_ sqlLiteral: SQLLiteral) -> Self {
self.init(impl: .literal(sqlLiteral))
}
@@ -104,9 +108,29 @@ extension SQLSelection {
""")
}
}
}
extension SQLSelection {
/// Support for `count(selection)`.
/// TODO: deprecate `count(selection)`, and get rid of this property.
var countExpression: SQLExpression {
switch impl {
case .allColumns,
.allCTEColumns:
return .countAll
case .qualifiedAllColumns,
.qualifiedAllCTEColumns:
// COUNT(player.*) is not valid SQL
fatalError("Uncountable selection")
case let .expression(expression),
let .aliasedExpression(expression, _):
return .count(expression)
case let .literal(sqlLiteral):
return .count(sqlLiteral.sqlExpression)
}
}
/// If the selection can be counted, return how to count it.
func count(distinct: Bool) -> SQLCount? {
switch impl {
@@ -182,9 +206,7 @@ extension SQLSelection {
""")
}
}
}
extension SQLSelection {
/// Returns the SQL that feeds the selection of a `SELECT` statement.
///
/// For example:
@@ -221,9 +243,7 @@ extension SQLSelection {
return try sqlLiteral.sql(context)
}
}
}
extension SQLSelection {
/// Returns true if the selection is an aggregate.
///
/// When in doubt, returns false.
@@ -252,9 +272,7 @@ extension SQLSelection {
return false
}
}
}
extension SQLSelection {
/// Returns a qualified selection
func qualified(with alias: TableAlias) -> SQLSelection {
switch impl {
+8 -8
View File
@@ -6,16 +6,16 @@ public struct SQLSubquery {
/// A literal SQL query
case literal(SQLLiteral)
/// A query interface query
case query(SQLQuery)
/// A query interface relation
case relation(SQLRelation)
}
static func literal(_ sqlLiteral: SQLLiteral) -> Self {
self.init(impl: .literal(sqlLiteral))
}
static func query(_ query: SQLQuery) -> Self {
self.init(impl: .query(query))
static func relation(_ relation: SQLRelation) -> Self {
self.init(impl: .relation(relation))
}
}
@@ -48,8 +48,8 @@ extension SQLSubquery {
let statement = try db.cachedSelectStatement(sql: sql)
return statement.columnCount
case let .query(query):
return try SQLQueryGenerator(query: query).columnsCount(db)
case let .relation(relation):
return try SQLQueryGenerator(relation: relation).columnsCount(db)
}
}
}
@@ -77,8 +77,8 @@ extension SQLSubquery {
case let .literal(sqlLiteral):
return try sqlLiteral.sql(context)
case let .query(query):
return try SQLQueryGenerator(query: query, forSingleResult: false).requestSQL(context)
case let .relation(relation):
return try SQLQueryGenerator(relation: relation).requestSQL(context)
}
}
}
@@ -1,12 +1,7 @@
/// SQLQueryGenerator is able to generate an SQL SELECT query.
struct SQLQueryGenerator: Refinable {
fileprivate private(set) var relation: SQLQualifiedRelation
private let isDistinct: Bool
private let groupPromise: DatabasePromise<[SQLExpression]>?
private let havingExpressionPromise: DatabasePromise<SQLExpression?>
private let limit: SQLLimit?
private let singleResult: Bool
private let ctes: OrderedDictionary<String, SQLCTE>
// For database region
private let prefetchedAssociations: [_SQLAssociation]
@@ -15,49 +10,12 @@ struct SQLQueryGenerator: Refinable {
/// - parameter singleResult: A hint as to whether the query should be
/// optimized for a single result.
init(
query: SQLQuery,
relation: SQLRelation,
forSingleResult singleResult: Bool = false)
{
// To generate SQL, we need a "qualified" relation, where all tables,
// expressions, etc, are identified with table aliases.
//
// All those aliases let us disambiguate tables at the SQL level, and
// prefix columns names. For example, the following request...
//
// Book.filter(Column("kind") == Book.Kind.novel)
// .including(optional: Book.author)
// .including(optional: Book.translator)
// .annotated(with: Book.awards.count)
//
// ... generates the following SQL, where all identifiers are correctly
// disambiguated and qualified:
//
// SELECT book.*, person1.*, person2.*, COUNT(DISTINCT award.id)
// FROM book
// LEFT JOIN person person1 ON person1.id = book.authorId
// LEFT JOIN person person2 ON person2.id = book.translatorId
// LEFT JOIN award ON award.bookId = book.id
// GROUP BY book.id
// WHERE book.kind = 'novel'
relation = SQLQualifiedRelation(query.relation)
// Qualify group expressions and having clause with the relation alias.
//
// This turns `GROUP BY id` INTO `GROUP BY book.id`, and
// `HAVING MAX(year) < 2000` INTO `HAVING MAX(book.year) < 2000`.
let sourceAlias = relation.source.alias
groupPromise = query.groupPromise?.map {
$0.map { $0.qualified(with: sourceAlias) }
}
havingExpressionPromise = query.havingExpressionPromise.map {
$0.map { $0.qualified(with: sourceAlias) }
}
limit = query.limit
isDistinct = query.isDistinct
self.relation = SQLQualifiedRelation(relation)
self.prefetchedAssociations = relation.prefetchedAssociations
self.singleResult = singleResult
prefetchedAssociations = query.relation.prefetchedAssociations
ctes = query.ctes
}
func requestSQL(_ context: SQLGenerationContext) throws -> String {
@@ -66,7 +24,7 @@ struct SQLQueryGenerator: Refinable {
var sql = try commonTableExpressionsPrefix(context)
sql += "SELECT"
if isDistinct {
if relation.isDistinct {
sql += " DISTINCT"
}
@@ -88,13 +46,13 @@ struct SQLQueryGenerator: Refinable {
}
}
let filter = try relation.filterPromise.resolve(context.db)
let filter = try relation.filterPromise?.resolve(context.db)
if let filter = filter {
sql += " WHERE "
sql += try filter.sql(context)
}
let groupExpressions = try groupPromise?.resolve(context.db) ?? []
let groupExpressions = try relation.groupPromise?.resolve(context.db) ?? []
if !groupExpressions.isEmpty {
sql += " GROUP BY "
sql += try groupExpressions
@@ -102,7 +60,7 @@ struct SQLQueryGenerator: Refinable {
.joined(separator: ", ")
}
if let havingExpression = try havingExpressionPromise.resolve(context.db) {
if let havingExpression = try relation.havingExpressionPromise?.resolve(context.db) {
sql += " HAVING "
sql += try havingExpression.sql(context)
}
@@ -115,8 +73,8 @@ struct SQLQueryGenerator: Refinable {
.joined(separator: ", ")
}
var limit = self.limit
if try singleResult && !expectsSingleResult(
var limit = relation.limit
if try limit == nil && singleResult && !expectsSingleResult(
context.db,
selection: selection,
filter: filter,
@@ -199,7 +157,7 @@ struct SQLQueryGenerator: Refinable {
}
// The filter knows better
guard let filter = try relation.filterPromise.resolve(db),
guard let filter = try relation.filterPromise?.resolve(db),
let rowIDs = try filter.identifyingRowIDs(db, for: relation.source.alias)
else {
return selectedRegion
@@ -255,12 +213,12 @@ struct SQLQueryGenerator: Refinable {
var sql = try commonTableExpressionsPrefix(context)
sql += try "DELETE FROM " + relation.source.sql(context)
if let filter = try relation.filterPromise.resolve(db) {
if let filter = try relation.filterPromise?.resolve(db) {
sql += " WHERE "
sql += try filter.sql(context)
}
if let limit = limit {
if let limit = relation.limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY "
@@ -341,12 +299,12 @@ struct SQLQueryGenerator: Refinable {
.map { try $0.sql(context) }
.joined(separator: ", ")
if let filter = try relation.filterPromise.resolve(db) {
if let filter = try relation.filterPromise?.resolve(db) {
sql += " WHERE "
sql += try filter.sql(context)
}
if let limit = limit {
if let limit = relation.limit {
let orderings = try relation.ordering.resolve(db)
if !orderings.isEmpty {
sql += " ORDER BY "
@@ -416,15 +374,15 @@ struct SQLQueryGenerator: Refinable {
}
private func commonTableExpressionsPrefix(_ context: SQLGenerationContext) throws -> String {
if ctes.isEmpty {
if relation.ctes.isEmpty {
return ""
}
var sql = "WITH "
if ctes.values.contains(where: \.isRecursive) {
if relation.ctes.values.contains(where: \.isRecursive) {
sql += "RECURSIVE "
}
sql += try ctes
sql += try relation.ctes
.map { tableName, cte in
var columnsSQL = ""
if let columns = cte.columns, !columns.isEmpty {
@@ -457,7 +415,7 @@ struct SQLQueryGenerator: Refinable {
private func grouping(_ db: Database) throws -> GroupingInfo {
// Empty group clause: no grouping
// SELECT * FROM player
guard let groupExpressions = try groupPromise?.resolve(db), groupExpressions.isEmpty == false else {
guard let groupExpressions = try relation.groupPromise?.resolve(db), groupExpressions.isEmpty == false else {
return .none
}
@@ -518,15 +476,40 @@ struct SQLQueryGenerator: Refinable {
}
}
/// A "qualified" relation, where all tables are identified with a table alias.
/// To generate SQL, we need a "qualified" relation, where all tables,
/// expressions, etc, are qualified with table aliases.
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// | | | | |
/// | | | | • ordering
/// | | | • filterPromise
/// | | • joins
/// | • source
/// • selectionPromise
/// All those aliases let us disambiguate tables at the SQL level, and
/// prefix columns names. For example, the following request...
///
/// Book.filter(Column("kind") == Book.Kind.novel)
/// .including(optional: Book.author)
/// .including(optional: Book.translator)
/// .annotated(with: Book.awards.count)
///
/// ... generates the following SQL, where all identifiers are correctly
/// disambiguated and qualified:
///
/// SELECT book.*, person1.*, person2.*, COUNT(DISTINCT award.id)
/// FROM book
/// LEFT JOIN person person1 ON person1.id = book.authorId
/// LEFT JOIN person person2 ON person2.id = book.translatorId
/// LEFT JOIN award ON award.bookId = book.id
/// GROUP BY book.id
/// WHERE book.kind = 'novel'
///
/// `SQLQualifiedRelation` contains the following information:
///
/// WITH ... -- ctes
/// SELECT ... -- selectionPromise
/// FROM ... -- source
/// JOIN ... -- joins
/// WHERE ... -- filterPromise
/// GROUP BY ... -- groupPromise
/// HAVING ... -- havingExpressionPromise
/// ORDER BY ... -- ordering
/// LIMIT ... -- limit
private struct SQLQualifiedRelation {
/// All aliases, including aliases of joined relations
var allAliases: [TableAlias] {
@@ -536,20 +519,14 @@ private struct SQLQualifiedRelation {
}
/// The source
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • source
let source: SQLQualifiedSource
/// The selection from source, not including selection of joined relations
private var sourceSelectionPromise: DatabasePromise<[SQLSelection]>
var isDistinct: Bool
/// The full selection, including selection of joined relations
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • selectionPromise
var selectionPromise: DatabasePromise<[SQLSelection]> {
DatabasePromise { db in
let selection = try self.sourceSelectionPromise.resolve(db)
@@ -560,34 +537,24 @@ private struct SQLQualifiedRelation {
}
}
/// The filtering clause
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • filterPromise
let filterPromise: DatabasePromise<SQLExpression?>
let filterPromise: DatabasePromise<SQLExpression>?
/// The ordering of source, not including ordering of joined relations
private let sourceOrdering: SQLRelation.Ordering
/// The full ordering, including orderings of joined relations
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • ordering
var ordering: SQLRelation.Ordering {
joins.reduce(sourceOrdering) {
$0.appending($1.value.relation.ordering)
}
}
/// The joins
///
/// SELECT ... FROM ... JOIN ... WHERE ... ORDER BY ...
/// |
/// • joins
private(set) var joins: OrderedDictionary<String, SQLQualifiedJoin>
let groupPromise: DatabasePromise<[SQLExpression]>?
let havingExpressionPromise: DatabasePromise<SQLExpression>?
let limit: SQLLimit?
let ctes: OrderedDictionary<String, SQLCTE>
init(_ relation: SQLRelation) {
// Qualify the source, so that it be disambiguated with an SQL alias
// if needed (when a select query uses the same table several times).
@@ -596,9 +563,8 @@ private struct SQLQualifiedRelation {
// this SQLQualifiedRelation generates SQL.
source = SQLQualifiedSource(relation.source)
// Qualify all joins, selection, filter, and ordering, so that all
// identifiers can be correctly disambiguated and qualified.
joins = relation.children.compactMapValues { SQLQualifiedJoin($0) }
// Qualify all selection, filter, etc, so that all identifiers
// can be correctly disambiguated and qualified.
let sourceAlias = source.alias
sourceSelectionPromise = relation.selectionPromise.map {
$0.map { $0.qualified(with: sourceAlias) }
@@ -607,6 +573,21 @@ private struct SQLQualifiedRelation {
$0.map { $0.qualified(with: sourceAlias) }
}
sourceOrdering = relation.ordering.qualified(with: sourceAlias)
groupPromise = relation.groupPromise?.map {
$0.map { $0.qualified(with: sourceAlias) }
}
havingExpressionPromise = relation.havingExpressionPromise.map {
$0.map { $0.qualified(with: sourceAlias) }
}
// Turns relation children into joins. `including(all:)` children are
// discarded on the way.
joins = relation.children.compactMapValues { SQLQualifiedJoin($0) }
// Copy other flags
limit = relation.limit
isDistinct = relation.isDistinct
ctes = relation.allCTEs
}
/// See SQLQueryGenerator.rowAdapter(_:)
@@ -669,14 +650,20 @@ private struct SQLQualifiedRelation {
return (adapter: adapter, endIndex: endIndex)
}
/// Removes all selections from joins
/// Sets the selection, removes all selections from joins, and clears the
/// `isDistinct` flag.
func selectOnly(_ selection: [SQLSelection]) -> Self {
let sourceSelectionPromise = DatabasePromise(value: selection.map {
$0.qualified(with: source.alias)
})
return self
.with(\.sourceSelectionPromise, sourceSelectionPromise)
.map(\.joins, { $0.mapValues { $0.selectOnly([]) } })
.with(\.isDistinct, false)
.map(\.joins, { joins in
joins.mapValues { join in
join.map(\.relation) { $0.selectOnly([]) }
}
})
}
}
@@ -738,11 +725,6 @@ private struct SQLQualifiedJoin: Refinable {
try sql(context, leftAlias: leftAlias, allowingInnerJoin: true)
}
/// Removes all selections from joins
func selectOnly(_ selection: [SQLSelection]) -> SQLQualifiedJoin {
map(\.relation) { $0.selectOnly(selection) }
}
private func sql(
_ context: SQLGenerationContext,
leftAlias: TableAlias,
@@ -779,7 +761,7 @@ private struct SQLQualifiedJoin: Refinable {
conditions.append(expression)
}
if let filter = try relation.filterPromise.resolve(context.db) {
if let filter = try relation.filterPromise?.resolve(context.db) {
conditions.append(filter.qualified(with: rightAlias))
}
@@ -373,4 +373,41 @@ extension TableRecord {
public static func aliased(_ alias: TableAlias) -> QueryInterfaceRequest<Self> {
all().aliased(alias)
}
/// Returns a request which embeds the common table expression.
///
/// If a common table expression with the same table name had already been
/// embedded, it is replaced by the new one.
///
/// For example, you can build a request that fetches all chats with their
/// latest post:
///
/// let latestMessageRequest = Message
/// .annotated(with: max(Column("date")))
/// .group(Column("chatID"))
///
/// let latestMessageCTE = CommonTableExpression(
/// named: "latestMessage",
/// request: latestMessageRequest)
///
/// let latestMessage = Chat.association(
/// to: latestMessageCTE,
/// on: { chat, latestMessage in
/// chat[Column("id")] == latestMessage[Column("chatID")]
/// })
///
/// // WITH latestMessage AS
/// // (SELECT *, MAX(date) FROM message GROUP BY chatID)
/// // SELECT chat.*, latestMessage.*
/// // FROM chat
/// // LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
/// let request = Chat
/// .with(latestMessageCTE)
/// .including(optional: latestMessage)
///
/// - parameter cte: A common table expression.
/// - returns: A request.
public static func with<RowDecoder>(_ cte: CommonTableExpression<RowDecoder>) -> QueryInterfaceRequest<Self> {
all().with(cte)
}
}
+2 -1
View File
@@ -51,7 +51,8 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
func singleValueContainer() throws -> SingleValueDecodingContainer {
guard let key = codingPath.last else {
fatalError("single value decoding from database row is not supported")
// Decoding an array of scalars from rows: pick the first column
return ColumnDecoder<R>(row: row, columnIndex: 0, codingPath: codingPath)
}
guard let index = row.index(forColumn: key.stringValue) else {
// Don't use DecodingError.keyNotFound:
+52
View File
@@ -118,6 +118,58 @@ struct OrderedDictionary<Key: Hashable, Value> {
let keys = self.keys.filter(dictionary.keys.contains)
return OrderedDictionary(keys: keys, dictionary: dictionary)
}
mutating func merge<S>(
_ other: S,
uniquingKeysWith combine: (Value, Value) throws -> Value)
rethrows
where S: Sequence, S.Element == (Key, Value)
{
for (key, value) in other {
if let current = self[key] {
self[key] = try combine(current, value)
} else {
self[key] = value
}
}
}
mutating func merge<S>(
_ other: S,
uniquingKeysWith combine: (Value, Value) throws -> Value)
rethrows
where S: Sequence, S.Element == (key: Key, value: Value)
{
for (key, value) in other {
if let current = self[key] {
self[key] = try combine(current, value)
} else {
self[key] = value
}
}
}
func merging<S>(
_ other: S,
uniquingKeysWith combine: (Value, Value) throws -> Value)
rethrows -> OrderedDictionary<Key, Value>
where S: Sequence, S.Element == (Key, Value)
{
var result = self
try result.merge(other, uniquingKeysWith: combine)
return result
}
func merging<S>(
_ other: S,
uniquingKeysWith combine: (Value, Value) throws -> Value)
rethrows -> OrderedDictionary<Key, Value>
where S: Sequence, S.Element == (key: Key, value: Value)
{
var result = self
try result.merge(other, uniquingKeysWith: combine)
return result
}
}
extension OrderedDictionary: Collection {
+15 -1
View File
@@ -119,8 +119,22 @@ where
subscription.request(currentDemand)
}
case .waitingForRequest, .subscribed, .finished:
case .waitingForRequest, .subscribed:
preconditionFailure()
case .finished:
// We receive the upstream subscription requested by
// `upstream.receive(subscriber: self)` above.
//
// But self has been cancelled since, so let's cancel this
// upstream subscription that has turned purposeless.
//
// This cancellation avoids the bug described in
// https://github.com/groue/GRDB.swift/pull/932
// TODO: write a regression test.
sideEffect = {
subscription.cancel()
}
}
}
}
-6
View File
@@ -256,8 +256,6 @@
5656A8942295BD56001FF3FF /* SQLFunctions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84C2295BD56001FF3FF /* SQLFunctions.swift */; };
5656A8972295BD56001FF3FF /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84E2295BD56001FF3FF /* SQLRelation.swift */; };
5656A8982295BD56001FF3FF /* SQLRelation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A84E2295BD56001FF3FF /* SQLRelation.swift */; };
5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8502295BD56001FF3FF /* SQLQuery.swift */; };
5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8502295BD56001FF3FF /* SQLQuery.swift */; };
5656A8A72295BF44001FF3FF /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */; };
5656A8A82295BF44001FF3FF /* DatabasePromise.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5656A8A52295BF44001FF3FF /* DatabasePromise.swift */; };
5657AABB1D107001006283EF /* NSData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5657AAB81D107001006283EF /* NSData.swift */; };
@@ -907,7 +905,6 @@
5656A84A2295BD56001FF3FF /* Column.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Column.swift; sourceTree = "<group>"; };
5656A84C2295BD56001FF3FF /* SQLFunctions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLFunctions.swift; sourceTree = "<group>"; };
5656A84E2295BD56001FF3FF /* SQLRelation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLRelation.swift; sourceTree = "<group>"; };
5656A8502295BD56001FF3FF /* SQLQuery.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SQLQuery.swift; sourceTree = "<group>"; };
5656A8A52295BF44001FF3FF /* DatabasePromise.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePromise.swift; sourceTree = "<group>"; };
5657AAB81D107001006283EF /* NSData.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NSData.swift; sourceTree = "<group>"; };
5657AB0E1D10899D006283EF /* URL.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = URL.swift; sourceTree = "<group>"; };
@@ -1549,7 +1546,6 @@
5656A84C2295BD56001FF3FF /* SQLFunctions.swift */,
5656A8462295BD56001FF3FF /* SQLOperators.swift */,
5656A8452295BD56001FF3FF /* SQLOrdering.swift */,
5656A8502295BD56001FF3FF /* SQLQuery.swift */,
5656A84E2295BD56001FF3FF /* SQLRelation.swift */,
568ECB0C25D904CA00B71526 /* SQLSelection.swift */,
568ECB3425D91CEE00B71526 /* SQLSubquery.swift */,
@@ -2355,7 +2351,6 @@
F3BA80141CFB2876003DC1BA /* DatabaseValueConvertible.swift in Sources */,
5656A8702295BD56001FF3FF /* Association.swift in Sources */,
563B8F9C249E74E5007A48C9 /* Trace.swift in Sources */,
5656A89C2295BD56001FF3FF /* SQLQuery.swift in Sources */,
5698AD261DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5656A85C2295BD56001FF3FF /* TableDefinition.swift in Sources */,
5656A8562295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */,
@@ -2713,7 +2708,6 @@
F3BA80701CFB2E55003DC1BA /* DatabaseValueConvertible.swift in Sources */,
5656A86F2295BD56001FF3FF /* Association.swift in Sources */,
563B8F9B249E74E5007A48C9 /* Trace.swift in Sources */,
5656A89B2295BD56001FF3FF /* SQLQuery.swift in Sources */,
5698AD231DABAEFA0056AF8C /* FTS5WrapperTokenizer.swift in Sources */,
5656A85B2295BD56001FF3FF /* TableDefinition.swift in Sources */,
5656A8552295BD56001FF3FF /* FTS5+QueryInterface.swift in Sources */,
+3 -3
View File
@@ -431,10 +431,10 @@ ifdef JAZZY
--author 'Gwendal Roué' \
--author_url https://github.com/groue \
--github_url https://github.com/groue/GRDB.swift \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.5.0 \
--module-version 5.5.0 \
--github-file-prefix https://github.com/groue/GRDB.swift/tree/v5.6.0 \
--module-version 5.6.0 \
--module GRDB \
--root-url http://groue.github.io/GRDB.swift/docs/5.5/ \
--root-url http://groue.github.io/GRDB.swift/docs/5.6/ \
--output Documentation/Reference \
--xcodebuild-arguments -project,GRDB.xcodeproj,-scheme,GRDBiOS
else
+55 -27
View File
@@ -11,13 +11,13 @@
---
**Latest release**: March 3, 2021 • version 5.5.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
**Latest release**: March 12, 2021 • version 5.6.0 • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 4 to GRDB 5](Documentation/GRDB5MigrationGuide.md)
**Requirements**: iOS 10.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ &bull; SQLite 3.8.5+ &bull; Swift 5.2+ / Xcode 11.4+
| Swift version | GRDB version |
| -------------- | ----------------------------------------------------------- |
| **Swift 5.2+** | **v5.5.0** |
| **Swift 5.2+** | **v5.6.0** |
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
| Swift 5 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
| Swift 4.2 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
@@ -278,7 +278,7 @@ Documentation
#### Reference
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.5/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
- [GRDB Reference](http://groue.github.io/GRDB.swift/docs/5.6/index.html) (generated by [Jazzy](https://github.com/realm/jazzy))
#### Getting Started
@@ -472,7 +472,7 @@ let dbQueue = try DatabaseQueue(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.6/Structs/Configuration.html) for more details.
## Database Pools
@@ -552,7 +552,7 @@ let dbPool = try DatabasePool(
configuration: config)
```
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html) for more details.
See [Configuration](http://groue.github.io/GRDB.swift/docs/5.6/Structs/Configuration.html) for more details.
Database pools are more memory-hungry than database queues. See [Memory Management](#memory-management) for more information.
@@ -612,7 +612,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
The `?` and colon-prefixed keys like `:score` in the SQL query are the **statements arguments**. You pass arguments with arrays or dictionaries, as in the example above. See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.6/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
You can also embed query arguments right into your SQL queries, with the `literal` argument label, as in the example below. See [SQL Interpolation] for more details.
@@ -815,7 +815,39 @@ try dbQueue.read { db in
- **Cursors are granted with direct access to SQLite,** unlike arrays and sets that have to take the time to copy database values. If you look after extra performance, you may prefer cursors.
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.5/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
- **Cursors can feed Swift collections.**
You will most of the time use `fetchAll` or `fetchSet` when you want an array or a set. For more specific needs, you may prefer one of the initializers below. All of them accept an extra optional `minimumCapacity` argument which helps optimizing your app when you have an idea of the number of elements in a cursor (the built-in `fetchAll` and `fetchSet` do not perform such an optimization).
**Arrays** and all types conforming to `RangeReplaceableCollection`:
```swift
// [String]
let cursor = try String.fetchCursor(db, ...)
let array = try Array(cursor)
```
**Sets**:
```swift
// Set<Int>
let cursor = try Int.fetchCursor(db, ...)
let set = try Set(cursor)
```
**Dictionaries**:
```swift
// [Int64: [Player]]
let cursor = try Player.fetchCursor(db)
let dictionary = try Dictionary(grouping: cursor, by: { $0.teamID })
// [Int64: Player]
let cursor = try Player.fetchCursor(db).map { ($0.id, $0) }
let dictionary = try Dictionary(uniqueKeysWithValues: cursor)
```
- **Cursors adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/5.6/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift.** As such, cursors come with many convenience methods: `compactMap`, `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`:
```swift
// Prints all Github links
@@ -830,12 +862,8 @@ try dbQueue.read { db in
.map { row in
CLLocationCoordinate2D(latitude: row[0], longitude: row[1])
}
// Turn cursors into arrays or sets:
let array = try Array(cursor)
let set = try Set(cursor)
```
- **Cursors are not Swift sequences.** That's because Swift sequences can't handle iteration errors, when reading SQLite results may fail at any time.
- **Cursors require a little care**:
@@ -898,7 +926,7 @@ let rows = try Row.fetchAll(db,
arguments: ["name": "Arthur"])
```
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
See [Values](#values) for more information on supported arguments types (Bool, Int, String, Date, Swift enums, etc.), and [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.6/Structs/StatementArguments.html) for a detailed documentation of SQLite arguments.
Unlike row arrays that contain copies of the database rows, row cursors are close to the SQLite metal, and require a little care:
@@ -1183,7 +1211,7 @@ GRDB ships with built-in support for the following value types:
- Generally speaking, all types that adopt the [DatabaseValueConvertible](#custom-value-types) protocol.
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html):
Values can be used as [statement arguments](http://groue.github.io/GRDB.swift/docs/5.6/Structs/StatementArguments.html):
```swift
let url: URL = ...
@@ -1592,7 +1620,7 @@ try dbQueue.inDatabase { db in // or dbPool.writeWithoutTransaction
}
```
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html) configuration flag:
Transactions can't be left opened unless you set the [allowsUnsafeTransactions](http://groue.github.io/GRDB.swift/docs/5.6/Structs/Configuration.html) configuration flag:
```swift
// fatal error: A transaction has been left opened at the end of a database access
@@ -1706,7 +1734,7 @@ try dbQueue.write { db in
}
```
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
The `?` and colon-prefixed keys like `:name` in the SQL query are the statement arguments. You set them with arrays or dictionaries (arguments are actually of type [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.6/Structs/StatementArguments.html), which happens to adopt the ExpressibleByArrayLiteral and ExpressibleByDictionaryLiteral protocols).
```swift
updateStatement.arguments = ["name": "Arthur", "score": 1000]
@@ -2483,7 +2511,7 @@ try Place.fetchSet(db, sql: "SELECT ...", arguments:...) // Set<Place>
try Place.fetchOne(db, sql: "SELECT ...", arguments:...) // Place?
```
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html) for more information about the query arguments.
See [fetching methods](#fetching-methods) for information about the `fetchCursor`, `fetchAll`, `fetchSet` and `fetchOne` methods. See [StatementArguments](http://groue.github.io/GRDB.swift/docs/5.6/Structs/StatementArguments.html) for more information about the query arguments.
> :point_up: **Note**: for performance reasons, the same row argument to `init(row:)` is reused during the iteration of a fetch query. If you want to keep the row for later use, make sure to store a copy: `self.row = row.copy()`.
@@ -2864,7 +2892,7 @@ protocol EncodableRecord {
}
```
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.5/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.5/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.5/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
See [DatabaseDateDecodingStrategy](https://groue.github.io/GRDB.swift/docs/5.6/Enums/DatabaseDateDecodingStrategy.html), [DatabaseDateEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.6/Enums/DatabaseDateEncodingStrategy.html), and [DatabaseUUIDEncodingStrategy](https://groue.github.io/GRDB.swift/docs/5.6/Enums/DatabaseUUIDEncodingStrategy.html) to learn about all available strategies.
> :point_up: **Note**: there is no customization of uuid decoding, because UUID can already decode all its encoded variants (16-bytes blobs, and uuid strings).
@@ -4329,7 +4357,7 @@ Player // SELECT * FROM player
```
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.5/Structs/StatementArguments.html):
Raw SQL snippets are also accepted, with eventual [arguments](http://groue.github.io/GRDB.swift/docs/5.6/Structs/StatementArguments.html):
```swift
// SELECT DATE(creationDate), COUNT(*) FROM player WHERE name = 'Arthur' GROUP BY date(creationDate)
@@ -4427,8 +4455,8 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli
SQLite arithmetic operators are derived from their Swift equivalent:
```swift
// SELECT ((temperature * 1.8) + 32) AS farenheit FROM planet
Planet.select((temperatureColumn * 1.8 + 32).forKey("farenheit"))
// SELECT ((temperature * 1.8) + 32) AS fahrenheit FROM planet
Planet.select((temperatureColumn * 1.8 + 32).forKey("fahrenheit"))
```
> :point_up: **Note**: an expression like `nameColumn + "rrr"` will be interpreted by SQLite as a numerical addition (with funny results), not as a string concatenation. See the `concat` operator below.
@@ -5016,7 +5044,7 @@ try Player.customRequest().fetchAll(db) // [Player]
- The `adapted(_:)` method eases the consumption of complex rows with [row adapters](#row-adapters). See [Joined Queries Support](#joined-queries-support) for some sample code that uses this method.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.5/Structs/AnyFetchRequest.html): a type-erased request.
- [AnyFetchRequest](http://groue.github.io/GRDB.swift/docs/5.6/Structs/AnyFetchRequest.html): a type-erased request.
## Joined Queries Support
@@ -6190,7 +6218,7 @@ After `stopObservingDatabaseChangesUntilNextTransaction()`, the `databaseDidChan
### DatabaseRegion
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.5/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
**[DatabaseRegion](https://groue.github.io/GRDB.swift/docs/5.6/Structs/DatabaseRegion.html) is a type that helps observing changes in the results of a database [request](#requests)**.
A request knows which database modifications can impact its results. It can communicate this information to [transaction observers](#transactionobserver-protocol) by the way of a DatabaseRegion.
@@ -6200,7 +6228,7 @@ DatabaseRegion fuels, for example, [ValueObservation and DatabaseRegionObservati
For example, if you observe the region of `Player.select(max(Column("score")))`, then you'll get be notified of all changes performed on the `score` column of the `player` table (updates, insertions and deletions), even if they do not modify the value of the maximum score. However, you will not get any notification for changes performed on other database tables, or updates to other columns of the player table.
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.5/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
For more details, see the [reference](http://groue.github.io/GRDB.swift/docs/5.6/Structs/DatabaseRegion.html#/s:4GRDB14DatabaseRegionV10isModified2bySbAA0B5EventV_tF).
#### The DatabaseRegionConvertible Protocol
@@ -7320,7 +7348,7 @@ try snapshot2.read { db in
### DatabaseWriter and DatabaseReader Protocols
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.5/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.5/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
Both DatabaseQueue and DatabasePool adopt the [DatabaseReader](http://groue.github.io/GRDB.swift/docs/5.6/Protocols/DatabaseReader.html) and [DatabaseWriter](http://groue.github.io/GRDB.swift/docs/5.6/Protocols/DatabaseWriter.html) protocols. DatabaseSnapshot adopts DatabaseReader only.
These protocols provide a unified API that let you write generic code that targets all concurrency modes. They fuel, for example:
@@ -7995,7 +8023,7 @@ When this is the case, there are two possible explanations:
try db.execute(sql: "UPDATE player SET name = ?", arguments: [name])
```
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.5/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
For more information, see [Double-quoted String Literals Are Accepted](https://sqlite.org/quirks.html#dblquote), and [Configuration.acceptsDoubleQuotedStringLiterals](http://groue.github.io/GRDB.swift/docs/5.6/Structs/Configuration.html#/s:4GRDB13ConfigurationV33acceptsDoubleQuotedStringLiteralsSbvp).
@@ -8157,4 +8185,4 @@ This chapter has been superseded by [ValueObservation] and [DatabaseRegionObserv
[Sharing a Database]: Documentation/SharingADatabase.md
[FAQ]: #faq
[Database Observation]: #database-changes-observation
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.5/Structs/SQLRequest.html
[SQLRequest]: http://groue.github.io/GRDB.swift/docs/5.6/Structs/SQLRequest.html
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>5.5.0</string>
<string>5.6.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
+2
View File
@@ -15,6 +15,8 @@
## Features
- [ ] Property wrapper that decodes dictionaries (but how to tell the key column?)
- [X] See if SQLITE_FCNTL_DATA_VERSION could help working around the lack of snapshots in order to avoid double initial fetch of ValueObservation. Result: no, it does not look it returns values that are comparable between two distinct SQLite connections (from the initial reader, and from the writer thhat starts the observation)
- [ ] Grab all FTS tokens in a string
- [ ] GRDB 6: decoding errors
- [ ] GRDB 6: conflict resolution in persistence methods
@@ -230,6 +230,86 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
}
}
func testIncludingAllHasManyScalar() 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")))
.orderByPrimaryKey()
// Array
do {
struct Record: FetchableRecord, Decodable, Equatable {
var a: A
var bs: [Int64]
}
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [1]),
Record(
a: A(row: ["cola1": 2, "cola2": "a2"]),
bs: [2]),
Record(
a: A(row: ["cola1": 3, "cola2": "a3"]),
bs: []),
])
}
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [1]))
}
}
// Set
do {
struct Record: FetchableRecord, Decodable, Equatable {
var a: A
var bs: Set<Int64>
}
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [1]),
Record(
a: A(row: ["cola1": 2, "cola2": "a2"]),
bs: [2]),
Record(
a: A(row: ["cola1": 3, "cola2": "a3"]),
bs: []),
])
}
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [1]))
}
}
}
}
}
func testIncludingAllHasManyIncludingAllHasMany() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.read { db in
@@ -157,6 +157,37 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testIncludingAllHasManyScalar() 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")))
.orderByPrimaryKey()
sqlQueries.removeAll()
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "a" ORDER BY "cola1"
""",
"""
SELECT DISTINCT "colb2", "colb2" AS "grdb_colb2" \
FROM "b" \
WHERE "colb2" IN (1, 2, 3) \
ORDER BY "colb2"
"""])
}
}
}
func testIncludingAllHasManyWithCompoundForeignKey() throws {
// We can use the CTE technique
let dbQueue = try makeDatabaseQueue()
@@ -1720,6 +1751,205 @@ class AssociationPrefetchingSQLTests: GRDBTestCase {
}
}
func testAggregate() throws {
struct Award: TableRecord { }
struct Player: TableRecord {
static let awards = hasMany(Award.self)
}
struct Team: TableRecord {
static let players = hasMany(Player.self)
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("teamId")
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("playerId")
t.column("parentId", .integer).references("team")
t.column("score")
t.column("category")
}
try db.create(table: "award") { t in
t.autoIncrementedPrimaryKey("awardId")
t.column("playerId", .integer).references("player")
}
try db.execute(sql: "INSERT INTO team DEFAULT VALUES")
do {
// Group an association
sqlQueries.removeAll()
let association = Team.players.select(max(Column("score"))).group(Column("category"))
let request = Team.including(all: association)
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "team"
""",
"""
SELECT MAX("score"), "parentId" AS "grdb_parentId" \
FROM "player" \
WHERE "parentId" = 1 \
GROUP BY "category"
"""])
}
do {
// Filter an association with an association aggregate
sqlQueries.removeAll()
let association = Team.players.having(Player.awards.isEmpty)
let request = Team.including(all: association)
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "team"
""",
"""
SELECT "player".*, "player"."parentId" AS "grdb_parentId" \
FROM "player" \
LEFT JOIN "award" ON "award"."playerId" = "player"."playerId" \
WHERE "player"."parentId" = 1 \
GROUP BY "player"."playerId" \
HAVING COUNT(DISTINCT "award"."awardId") = 0
"""])
}
do {
// Annotate an association with an association aggregate
sqlQueries.removeAll()
let association = Team.players.annotated(with: Player.awards.count)
let request = Team.including(all: association)
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "team"
""",
"""
SELECT "player".*, COUNT(DISTINCT "award"."awardId") AS "awardCount", "player"."parentId" AS "grdb_parentId" \
FROM "player" \
LEFT JOIN "award" ON "award"."playerId" = "player"."playerId" \
WHERE "player"."parentId" = 1 \
GROUP BY "player"."playerId"
"""])
}
}
}
func testDistinct() throws {
struct Player: TableRecord { }
struct Team: TableRecord {
static let players = hasMany(Player.self)
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("teamId")
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("playerId")
t.column("parentId", .integer).references("team")
}
try db.execute(sql: "INSERT INTO team DEFAULT VALUES")
do {
sqlQueries.removeAll()
let association = Team.players.distinct()
let request = Team.including(all: association)
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "team"
""",
"""
SELECT DISTINCT *, "parentId" AS "grdb_parentId" \
FROM "player" \
WHERE "parentId" = 1
"""])
}
}
}
func testLimit() throws {
struct Player: TableRecord { }
struct Team: TableRecord {
static let players = hasMany(Player.self)
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("teamId")
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("playerId")
t.column("parentId", .integer).references("team")
}
try db.execute(sql: "INSERT INTO team DEFAULT VALUES")
do {
sqlQueries.removeAll()
let association = Team.players.limit(10, offset: 5)
let request = Team.including(all: association)
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "team"
""",
"""
SELECT *, "parentId" AS "grdb_parentId" \
FROM "player" \
WHERE "parentId" = 1 \
LIMIT 10 OFFSET 5
"""])
}
}
}
func testCTE() throws {
struct Player: TableRecord { }
struct Team: TableRecord {
static let players = hasMany(Player.self)
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.write { db in
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("teamId")
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("playerId")
t.column("parentId", .integer).references("team")
}
try db.execute(sql: "INSERT INTO team DEFAULT VALUES")
do {
sqlQueries.removeAll()
let cte = CommonTableExpression(named: "cte", sql: "SELECT 42")
let association = Team.players.with(cte).filter(Column("playerId") == cte.all())
let request = Team.including(all: association)
_ = try Row.fetchAll(db, request)
let selectQueries = sqlQueries.filter(isSelectQuery)
XCTAssertEqual(selectQueries, [
"""
SELECT * FROM "team"
""",
"""
WITH "cte" AS (SELECT 42) \
SELECT *, "parentId" AS "grdb_parentId" \
FROM "player" \
WHERE ("playerId" = (SELECT * FROM "cte")) AND ("parentId" = 1)
"""])
}
}
}
// Return SELECT queries, but omit schema queries.
private func isSelectQuery(_ query: String) -> Bool {
return query.contains("SELECT") && !query.contains("sqlite_") && !query.contains("pragma_table_xinfo")
@@ -619,4 +619,164 @@ class CommonTableExpressionTests: GRDBTestCase {
""")
}
}
func testAssociation() throws {
try makeDatabaseQueue().write { db in
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("id")
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("teamId", .integer).references("team")
}
try db.create(table: "award") { t in
t.autoIncrementedPrimaryKey("id")
t.column("playerId", .integer).references("player")
}
struct Team: TableRecord { }
struct Player: TableRecord {
static let team = belongsTo(Team.self)
}
struct Award: TableRecord {
static let player = belongsTo(Player.self)
static let team = hasOne(Team.self, through: player, using: Player.team)
}
do {
// CTE on association
let cte = CommonTableExpression(named: "cte", sql: "SELECT 1")
let request = Award
.joining(optional: Award.player.with(cte))
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 1) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId"
""")
}
do {
// CTE on hasOneThrough association
let cte = CommonTableExpression(named: "cte", sql: "SELECT 1")
let request = Award
.joining(optional: Award.team.with(cte))
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 1) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId" \
LEFT JOIN "team" ON "team"."id" = "player"."teamId"
""")
}
do {
// CTE on pivot of hasOneThrough association
let cte = CommonTableExpression(named: "cte", sql: "SELECT 1")
let team = Award.hasOne(Team.self, through: Award.player.with(cte), using: Player.team)
let request = Award
.joining(optional: team)
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 1) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId" \
LEFT JOIN "team" ON "team"."id" = "player"."teamId"
""")
}
do {
// Distinct CTEs on association and main request
let cte1 = CommonTableExpression(named: "cte1", sql: "SELECT 1")
let cte2 = CommonTableExpression(named: "cte2", sql: "SELECT 2")
let request = Award
.with(cte1)
.joining(optional: Award.player.with(cte2))
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte1" AS (SELECT 1), \
"cte2" AS (SELECT 2) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId"
""")
}
do {
// Conflicting CTEs. The rule is: the last one wins.
do {
// Conflicting CTE on association and main request
let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1")
let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2")
let request = Award
.with(cte1)
.joining(optional: Award.player.with(cte2))
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 2) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId"
""")
}
do {
// Conflicting CTE on two associations
let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1")
let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2")
let request = Award
.joining(optional: Award.player.with(cte1))
.joining(optional: Award.team.with(cte2))
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 2) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId" \
LEFT JOIN "team" ON "team"."id" = "player"."teamId"
""")
}
do {
// Conflicting CTE on two associations
let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1")
let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2")
let request = Award
.joining(optional: Award.team.with(cte1))
.joining(optional: Award.player.with(cte2))
_ = try Row.fetchAll(db, request)
// There's a trick here. The last CTE wins, and the last cte
// is cte1: it is plugged on top of Award.player, where cte2
// is attached.
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 1) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" ON "player"."id" = "award"."playerId" \
LEFT JOIN "team" ON "team"."id" = "player"."teamId"
""")
}
do {
// Conflicting CTE on two associations
let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1")
let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2")
let request = Award
.joining(optional: Award.player.forKey("player1").with(cte1))
.joining(optional: Award.player.forKey("player2").with(cte2))
_ = try Row.fetchAll(db, request)
XCTAssertEqual(lastSQLQuery, """
WITH "cte" AS (SELECT 2) \
SELECT "award".* \
FROM "award" \
LEFT JOIN "player" "player1" ON "player1"."id" = "award"."playerId" \
LEFT JOIN "player" "player2" ON "player2"."id" = "award"."playerId"
""")
}
}
}
}
}
+58
View File
@@ -171,6 +171,46 @@ class CursorTests: GRDBTestCase {
}
}
func testRangeReplaceableCollection() throws {
func collect<Col, Cur>(_ cursor: Cur) throws -> Col
where Col: RangeReplaceableCollection, Cur: Cursor, Col.Element == Cur.Element
{
try Col(cursor)
}
func collect<Col, Cur>(_ cursor: Cur, minimumCapacity: Int) throws -> Col
where Col: RangeReplaceableCollection, Cur: Cursor, Col.Element == Cur.Element
{
try Col(cursor, minimumCapacity: minimumCapacity)
}
do {
let cursor = AnyCursor([1, 2, 1, 3])
let collection: [Int] = try collect(cursor)
XCTAssertEqual(collection, [1, 2, 1, 3])
}
do {
let cursor = AnyCursor([1, 2, 1, 3])
let collection: [Int] = try collect(cursor, minimumCapacity: 100)
XCTAssertEqual(collection, [1, 2, 1, 3])
}
}
func testSet() throws {
do {
let cursor = AnyCursor([1, 2, 1, 3])
let set = try Set(cursor)
XCTAssertEqual(set, [1, 2, 3])
}
do {
let cursor = AnyCursor([1, 2, 1, 3])
let set = try Set(cursor, minimumCapacity: 100)
XCTAssertEqual(set, [1, 2, 3])
}
}
func testDictionaryGrouping() throws {
do {
let cursor = AnyCursor<Int>([])
@@ -187,5 +227,23 @@ class CursorTests: GRDBTestCase {
let dictionary = try Dictionary(grouping: cursor, by: { $0 % 2 })
XCTAssertEqual(dictionary, [0: [4, 2], 1: [5, 3, 1]])
}
do {
let cursor = AnyCursor<Int>([1, 2, 3, 4, 5])
let dictionary = try Dictionary(minimumCapacity: 100, grouping: cursor, by: { $0 % 2 })
XCTAssertEqual(dictionary, [0: [2, 4], 1: [1, 3, 5]])
}
}
func testDictionaryUniqueKeysWithValues() throws {
do {
let cursor = AnyCursor([(1, "a"), (2, "b"), (3, "a")])
let dictionary = try Dictionary(uniqueKeysWithValues: cursor)
XCTAssertEqual(dictionary, [1: "a", 2: "b", 3: "a"])
}
do {
let cursor = AnyCursor([(1, "a"), (2, "b"), (3, "a")])
let dictionary = try Dictionary(minimumCapacity: 100, uniqueKeysWithValues: cursor)
XCTAssertEqual(dictionary, [1: "a", 2: "b", 3: "a"])
}
}
}
+23
View File
@@ -52,4 +52,27 @@ class DatabasePoolTests: GRDBTestCase {
XCTAssertFalse(fm.fileExists(atPath: path + "-wal"))
XCTAssertFalse(fm.fileExists(atPath: path + "-shm"))
}
// Regression test
func testIssue931() throws {
dbConfiguration.prepareDatabase { db in
var flag: CInt = 0
let code = withUnsafeMutablePointer(to: &flag) { flagP in
sqlite3_file_control(db.sqliteConnection, nil, SQLITE_FCNTL_PERSIST_WAL, flagP)
}
guard code == SQLITE_OK else {
throw DatabaseError(resultCode: ResultCode(rawValue: code))
}
}
let dbQueue = try makeDatabaseQueue()
var migrator = DatabaseMigrator()
migrator.registerMigration("v1", migrate: { _ in })
migrator.eraseDatabaseOnSchemaChange = true
try migrator.migrate(dbQueue)
// Trigger #931: the migrator creates a temporary database and
// calls `sqlite3_file_control` as part of the preparation function.
try migrator.migrate(dbQueue)
}
}
@@ -8,4 +8,53 @@ class OrderedDictionaryTests: GRDBTestCase {
dict["a", default: []].append("bar")
XCTAssertEqual(dict, ["a": ["foo", "bar"]])
}
func testMergingUniquingKeysWith() {
do {
let dict: OrderedDictionary = ["a": 1, "b": 2]
let otherDictionary = ["a": 3, "c": 4]
let otherOrderedDictionary: OrderedDictionary = ["a": 3, "c": 4]
let otherSequence = zip(["a", "c"], [3, 4])
do {
let result = dict.merging(otherDictionary, uniquingKeysWith: { (current, _) in current })
XCTAssertEqual(result, ["a": 1, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherOrderedDictionary, uniquingKeysWith: { (current, _) in current })
XCTAssertEqual(result, ["a": 1, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherSequence, uniquingKeysWith: { (current, _) in current })
XCTAssertEqual(result, ["a": 1, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherDictionary, uniquingKeysWith: { (_, new) in new })
XCTAssertEqual(result, ["a": 3, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherOrderedDictionary, uniquingKeysWith: { (_, new) in new })
XCTAssertEqual(result, ["a": 3, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherSequence, uniquingKeysWith: { (_, new) in new })
XCTAssertEqual(result, ["a": 3, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherDictionary, uniquingKeysWith: { $0 + $1 })
XCTAssertEqual(result, ["a": 4, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherOrderedDictionary, uniquingKeysWith: { $0 + $1 })
XCTAssertEqual(result, ["a": 4, "b": 2, "c": 4])
}
do {
let result = dict.merging(otherSequence, uniquingKeysWith: { $0 + $1 })
XCTAssertEqual(result, ["a": 4, "b": 2, "c": 4])
}
}
}
}
@@ -1,7 +1,6 @@
import XCTest
import GRDB
#warning("TODO: test decoding error")
// A type that adopts DatabaseValueConvertible and StatementColumnConvertible
private struct Fetched: DatabaseValueConvertible, StatementColumnConvertible, Hashable {
let int: Int