Compare commits

...
Author SHA1 Message Date
Gwendal Roué c93ba4fba8 WIP 2025-01-17 17:52:52 +01:00
Gwendal Roué ec40855466 Merge pull request #1697 from kevinlg/fix-typo-in-docs
Fix typo in Readme.md
2025-01-09 07:23:43 +01:00
Kevin LE GOFF 1cca3686f5 Fix typo in Readme.md 2025-01-09 00:01:48 +02:00
Gwendal Roué 1e354ba79c Delete the rationale for Sendable records
... because the reality is that I just don't know how to relax this requirement.

See:

- https://www.youtube.com/watch?v=JmrnE7HUaDE
- https://forums.swift.org/t/swiftserverconf-feedback-on-leveraging-structured-concurrency-in-your-applications/75176
2025-01-02 17:07:55 +01:00
Gwendal Roué 0ea5471b56 Merge pull request #1696 from groue/dev/sqlite-3.47.2
Bump custom SQLite to 3.47.2
2025-01-02 12:57:50 +01:00
Gwendal Roué b2e808b9e4 Bump custom SQLite to 3.47.2 2025-01-02 12:28:14 +01:00
Gwendal Roué ac0c085a4a Merge pull request #1695 from JasonnnW3000/master
Update LICENSE, fix copyright license year
2025-01-01 12:25:30 +01:00
JasonnnW3000 9f9f0d37dd Update LICENSE, fix license year
Signed-off-by: JasonnnW3000 <sufssl04@gmail.com>
2024-12-31 23:58:47 -05:00
Gwendal Roué 898e7b6abe Merge pull request #1662 from compnerd/c
Core: import `ucrt` on Windows for `strcmp`
2024-11-13 16:11:39 +01:00
Gwendal Roué 0fb599812f Merge pull request #1661 from compnerd/extensions
Foundation: elide extensions on Windows to match Linux
2024-11-13 16:11:10 +01:00
Saleem Abdulrasool 77a4d17940 Core: import ucrt on Windows for strcmp
This uses the deprecated `strcmp` interface on Windows, which requires
the C library to be imported. Add the missing import to allow building
on Windows.
2024-11-12 11:12:27 -08:00
Saleem Abdulrasool c865a847fd Foundation: elide extensions on Windows to match Linux
Similar to Linux, elide some extensions on Windows. This is required to
build this module on Windows.
2024-11-12 11:10:07 -08:00
Gwendal Roué 832bc1aa74 Merge pull request #1660 from nylki/patch-1
docs: fixes typos "FST"->"FTS"
2024-11-11 11:50:35 +01:00
Tom Brewe 910ca2d0ce docs: fixes typos "FST"->"FTS" 2024-11-01 20:16:44 +01:00
Gwendal Roué 3ecb5c5455 Remove compiler warning in demo app 2024-10-22 08:18:38 +02:00
Gwendal Roué 84d25dfc9d Merge branch 'development' 2024-10-13 18:54:36 +02:00
Gwendal Roué 5664c5a829 7.0.0-beta.6 2024-10-13 18:54:10 +02:00
Gwendal Roué 334a63aa4a Update links to database schema documentation 2024-10-13 17:58:57 +02:00
Gwendal Roué 7e506f6488 Merge pull request #1654 from groue/dev/SQLite-3.46.1
Bump custom SQLite builds to 3.46.1
2024-10-13 17:52:53 +02:00
Gwendal Roué 5341f139e5 Update the Swift badge 2024-10-13 13:55:18 +02:00
Gwendal Roué 917b7ecc90 Bump custom SQLite to 3.46.1 2024-10-13 12:50:56 +02:00
Gwendal Roué c396fc20be Merge branch 'development' 2024-10-13 12:18:03 +02:00
Gwendal Roué 73083c4f1b 7.0.0-beta.5 2024-10-13 12:17:37 +02:00
Gwendal Roué 2c12f0a5e6 Merge pull request #1652 from groue/dev/schema-doc
Enhance the database schema documentation
2024-10-13 11:33:25 +02:00
Gwendal Roué c97f633022 More documentation of database schema methods 2024-10-13 11:28:14 +02:00
Gwendal Roué 4315030af5 More tests for object existence checks 2024-10-13 11:12:27 +02:00
Gwendal Roué 13b6c9d36b Split database schema documentation into several files, and restore the overview of database schema features
Fixes #1623
2024-10-13 10:54:13 +02:00
Gwendal Roué 8aaeb253d2 Merge pull request #1653 from Jnosh/schema-changes-readonly
Fix DatabaseMigrator.hasSchemaChanges failing for readonly connections
2024-10-13 10:49:53 +02:00
Janosch Hildebrand a741fb38f0 Fix DatabaseMigrator.hasSchemaChanges failing for readonly connections 2024-10-12 18:36:15 +02:00
Gwendal Roué 2c49a69f43 Raise a fatal error when the users filters a database view by primary key
Fixes #1648
2024-10-12 15:41:36 +02:00
Gwendal Roué d6b50b2c54 Merge branch 'development' 2024-10-12 14:04:05 +02:00
Gwendal Roué ad983f7971 7.0.0-beta.4 2024-10-12 14:03:56 +02:00
Gwendal Roué 7cd075bbdc Merge pull request #1651 from groue/dev/hasSchemaChanges
Allow applications to handle DatabaseMigrator schema changes.
2024-10-12 14:01:01 +02:00
Gwendal Roué 0aa8498620 DatabaseMigrator.hasSchemaChanges 2024-10-12 12:40:36 +02:00
Gwendal Roué bccf312af6 Merge branch 'development' 2024-10-06 18:49:34 +02:00
Gwendal Roué 5b4a86b5f7 7.0.0-beta.3 2024-10-06 18:42:03 +02:00
Gwendal Roué 68d12916e6 Fix Swiftlint warning 2024-10-06 18:36:43 +02:00
Gwendal Roué 6a4f454464 Merge pull request #1649 from bok-/master
Add `DatabaseValueConvertible` tip for JSON columns
2024-10-06 18:30:23 +02:00
Gwendal Roué a9fa2871aa Document the requirements 2024-10-06 18:19:11 +02:00
Rob Amos 8c5396898a Add DatabaseValueConvertible tip 2024-10-06 23:18:13 +11:00
Gwendal Roué dd14710c86 Fix typo 2024-10-06 13:55:29 +02:00
Gwendal Roué 97c0c72702 Merge pull request #1645 from philmitchell/coalesce
Add coalesce free function and Row method
2024-10-06 13:55:02 +02:00
Gwendal Roué a17d72e04c Make the top-level coalesce function work with collections of size zero and one. 2024-10-06 12:53:22 +02:00
Gwendal Roué 761b00f9bc Test Row.coalesce with collections of size zero and one. 2024-10-06 12:45:38 +02:00
Gwendal Roué ac3278a38b Test top-level function coalesce like other top-level functions 2024-10-06 12:42:33 +02:00
Gwendal Roué 06c3ab0d16 Test Row.coalesce on all variants of Row 2024-10-06 12:42:10 +02:00
Gwendal Roué f38619ada8 Restore alphabetical order of SQL functions 2024-10-06 12:42:10 +02:00
Gwendal Roué 8cac458efc Use "real" column names in examples.
Also, remove "essential".
2024-10-06 12:42:10 +02:00
Gwendal Roué a13c1bec29 Add coalesce in DocC 2024-10-06 12:19:49 +02:00
Gwendal Roué c6781f46d2 Prefer Collection over Array
This allows the user to call those methods with an Array, or any other collection at hand (including lazy ones)

This change makes `return coalesce(columns.lazy.map { $0.name })` iterate lazily. Before this commit, `map` was returning a non-lazy Array.
2024-10-06 12:19:49 +02:00
Gwendal Roué fd04831586 Merge pull request #1644 from tayloraswift/enable-linux-build
use #if directives to conditionally `@preconcurrency import `the `Dispatch` module to enable building the package on linux
2024-10-06 11:45:59 +02:00
Phil Mitchell d7754fa79c Add coalesce free function and Row method 2024-09-30 13:10:59 +10:00
Dianna 5f2185a118 use #if directives to conditionally @preconcurrency import the Dispatch module to enable building the package on linux 2024-09-29 21:44:34 +00:00
Gwendal Roué dc03b8a29e Update links to GRDB7 documentation 2024-09-29 20:29:51 +02:00
Gwendal Roué a0c1de55c4 Enhance PlayerListModelTests 2024-09-29 17:10:05 +02:00
Gwendal Roué d1f5a37520 Enhance the demo app tests
Based on https://forums.swift.org/t/testing-closure-based-asynchronous-apis/73705/36
2024-09-29 15:46:18 +02:00
Gwendal Roué ed5f8c11ab 7.0.0-beta.2 2024-09-29 15:17:41 +02:00
Gwendal Roué afda0d1e7c Merge pull request #1643 from finestructure/patch-1
Update .spi.yml
2024-09-29 15:12:38 +02:00
Sven A. Schmidt 18c7f51a4e Update .spi.yml 2024-09-29 15:10:03 +02:00
Gwendal Roué a6b15684c3 Improve migration notes for ValueObservation 2024-09-29 13:27:07 +02:00
Gwendal Roué 9bdde6bc6f More links in GRDBDemo README 2024-09-29 13:04:36 +02:00
Gwendal Roué db9ef1bb27 Emphasize Swift concurrency recommendations in the migration guide 2024-09-29 12:12:57 +02:00
Gwendal Roué 2958020c69 De-emphasize the Record class in the migration guide 2024-09-29 12:10:26 +02:00
Gwendal Roué 895436a2a1 Mention companion libraries in the GRDB 7 migration guide 2024-09-29 12:07:34 +02:00
47 changed files with 1560 additions and 750 deletions

No files matched your search

+1
View File
@@ -2,3 +2,4 @@ version: 1
builder:
configs:
- documentation_targets: [GRDB]
swift_version: 6.0
+36 -3
View File
@@ -7,7 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 7.x Releases
- `7.0.0` Betas - [7.0.0-beta](#700-beta)
- `7.0.0` Betas - [7.0.0-beta](#700-beta) - [7.0.0-beta.2](#700-beta2) - [7.0.0-beta.3](#700-beta3) - [7.0.0-beta.4](#700-beta4) - [7.0.0-beta.5](#700-beta5) - [7.0.0-beta.6](#700-beta6)
#### 6.x Releases
@@ -131,6 +131,39 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 7.0.0-beta.6
Released October 13, 2024
- **New**: Bump custom SQLite builds to 3.46.1 by [@groue](https://github.com/groue) in [#1654](https://github.com/groue/GRDB.swift/pull/1654)
## 7.0.0-beta.5
Released October 13, 2024
- **Fixed**: Fix DatabaseMigrator.hasSchemaChanges failing for readonly connections by [@Jnosh](https://github.com/Jnosh) in [#1653](https://github.com/groue/GRDB.swift/pull/1653)
- **Documentation Update**: Enhance the database schema documentation by [@groue](https://github.com/groue) in [#1652](https://github.com/groue/GRDB.swift/pull/1652)
## 7.0.0-beta.4
Released October 12, 2024
- **New**: Allow applications to handle DatabaseMigrator schema changes by [@groue](https://github.com/groue) in [#1651](https://github.com/groue/GRDB.swift/pull/1651)
## 7.0.0-beta.3
Released October 6, 2024
- **Fix**: use #if directives to conditionally @preconcurrency import the Dispatch module to enable building the package on linux by [@tayloraswift](https://github.com/tayloraswift) in [#1644](https://github.com/groue/GRDB.swift/pull/1644)
- **New**: Add coalesce free function and Row method by [@philmitchell](https://github.com/philmitchell) in [#1645](https://github.com/groue/GRDB.swift/pull/1645)
- **Documentation Update**: Add `DatabaseValueConvertible` tip for JSON columns by [@bok-](https://github.com/bok-) in [#1649](https://github.com/groue/GRDB.swift/pull/1649)
## 7.0.0-beta.2
Released September 29, 2024
- **Fix**: Update .spi.yml by [@finestructure](https://github.com/finestructure) in [#1643](https://github.com/groue/GRDB.swift/pull/1643)
## 7.0.0-beta
Released September 29, 2024
@@ -139,11 +172,11 @@ Released September 29, 2024
[Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md) describes in detail how to bump the GRDB version in your application.
The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
The new [Swift Concurrency and GRDB](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/swiftconcurrency) guide explains how to best integrate GRDB and Swift Concurrency.
The [demo app](Documentation/DemoApps/) was rewritten from scratch in a brand new Xcode 16 project.
- **Breaking Change**: Bump requirements by [@groue](https://github.com/groue) in [#1598](https://github.com/groue/GRDB.swift/pull/1598) and [#1634](https://github.com/groue/GRDB.swift/pull/1634)
- **Breaking Change**: Bump requirements by [@groue](https://github.com/groue) in [#1598](https://github.com/groue/GRDB.swift/pull/1598) and [#1634](https://github.com/groue/GRDB.swift/pull/1634)
- **Breaking Change**: Enhance ergonomics of record methods that insert/save/upsert and fetch by [@groue](https://github.com/groue) in [#1599](https://github.com/groue/GRDB.swift/pull/1599)
- **Breaking Change**: Rename the CSQLite module to GRDBSQLite, and stop exporting the C SQLite functions by [@groue](https://github.com/groue) in [#1600](https://github.com/groue/GRDB.swift/pull/1600)
- **Breaking Change**: Perform all writes with immediate transactions by default by [@groue](https://github.com/groue) in [#1602](https://github.com/groue/GRDB.swift/pull/1602)
+1 -1
View File
@@ -3,7 +3,7 @@ Custom SQLite Builds
By default, GRDB uses the version of SQLite that ships with the target operating system.
**You can build GRDB with a custom build of [SQLite 3.44.0](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.47.2](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver).
@@ -67,18 +67,15 @@ extension AppDatabase {
/// Returns a database configuration suited for `AppDatabase`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
/// - parameter config: A base configuration.
static func makeConfiguration(_ config: Configuration = Configuration()) -> Configuration {
// var config = config
//
// Add custom SQL functions or collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
//
// Uncomment for enabling SQL logging if the `SQL_TRACE` environment variable is set.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/trace(options:_:)>
// if ProcessInfo.processInfo.environment["SQL_TRACE"] != nil {
@@ -6,41 +6,36 @@ struct PlayerListModelTests {
// MARK: - PlayerListModel.observePlayers tests
@Test(.timeLimit(.minutes(1)))
@MainActor func observation_started_after_player_creation() async throws {
// Given a PlayerListModel on a database that contains a player
@MainActor func observation_grabs_current_database_state() async throws {
// Given a PlayerListModel on a database that contains one player
let appDatabase = try makeEmptyTestDatabase()
var player = Player(name: "Arthur", score: 1000)
try appDatabase.savePlayer(&player)
let model = PlayerListModel(appDatabase: appDatabase)
// When we start observing the database
// When the model starts observing the database
model.observePlayers()
// Then the model eventually fetches the player.
// We poll because we do not know when the model will update its players.
await pollUntil {
model.players.isEmpty == false
}
#expect(model.players == [player])
// Then the model eventually has one player.
try await pollUntil { model.players.count == 1 }
}
@Test(.timeLimit(.minutes(1)))
@MainActor func observation_started_before_player_creation() async throws {
// Given a PlayerListModel that observes a empty database
@MainActor func observation_grabs_database_changes() async throws {
// Given a PlayerListModel that has one player
let appDatabase = try makeEmptyTestDatabase()
var player1 = Player(name: "Arthur", score: 1000)
try appDatabase.savePlayer(&player1)
let model = PlayerListModel(appDatabase: appDatabase)
model.observePlayers()
try await pollUntil { model.players.count == 1 }
// When we insert a player
var player = Player(name: "Arthur", score: 1000)
try appDatabase.savePlayer(&player)
// When we insert a second player
var player2 = Player(name: "Barbara", score: 800)
try appDatabase.savePlayer(&player2)
// Then the model eventually fetches the player.
// We poll because we do not know when the model will update its players.
await pollUntil {
model.players.isEmpty == false
}
#expect(model.players == [player])
// Then the model eventually has two players.
try await pollUntil { model.players.count == 2 }
}
@Test
@@ -68,14 +63,14 @@ struct PlayerListModelTests {
}
/// Convenience method that loops until a condition is met.
private func pollUntil(condition: @escaping @MainActor () async -> Bool) async {
await confirmation { confirmation in
private func pollUntil(condition: @escaping @MainActor () async -> Bool) async throws {
try await confirmation { confirmation in
while true {
if await condition() {
confirmation()
return
} else {
await Task.yield()
try await Task.sleep(for: .seconds(0.01))
}
}
}
+11 -1
View File
@@ -24,6 +24,8 @@ The topics covered in this demo are:
- [AppDatabase.swift](GRDBDemo/Database/AppDatabase.swift)
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasemigrator) in order to setup the database schema, and provides methods that read and write.
`AppDatabase` is [tested](GRDBDemoTests/AppDatabaseTests.swift).
- [Persistence.swift](GRDBDemo/Database/Persistence.swift)
@@ -33,4 +35,12 @@ The topics covered in this demo are:
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../../README.md#codable-records).
- [GRDBDemoTests](GRDBDemoTests)
- [PlayerListModel.swift](GRDBDemo/Views/PlayerListModel.swift)
`PlayerListModel` is an `@Observable` object that observes the database, displays always fresh values on screen, and performs actions.
`PlayerListModel` is [tested](GRDBDemoTests/PlayerListModelTests.swift).
- [PlayersNavigationView.swift](GRDBDemo/Views/PlayersNavigationView.swift)
`PlayersNavigationView` is the main navigation view of the application. It instantiates a `PlayerListModel` from the `AppDatabase` stored in the SwiftUI environment.
+2 -2
View File
@@ -3,7 +3,7 @@ FTS5 Tokenizers
**[FTS5](https://www.sqlite.org/fts5.html) is an extensible full-text search engine.**
GRDB lets you define your own custom FST5 tokenizers, and extend SQLite built-in tokenizers. Possible use cases are:
GRDB lets you define your own custom FTS5 tokenizers, and extend SQLite built-in tokenizers. Possible use cases are:
- Have "fi" match the ligature "&#xfb01;" (U+FB01)
- Have "first" match "1st"
@@ -95,7 +95,7 @@ let documents = try Document.matching(pattern).fetchAll(db)
## FTS5Tokenizer
**FST5Tokenizer** is the protocol for all FTS5 tokenizers.
**FTS5Tokenizer** is the protocol for all FTS5 tokenizers.
It only requires a tokenization method that matches the low-level `xTokenize` C function documented at https://www.sqlite.org/fts5.html#custom_tokenizers. We'll discuss it more when describing custom tokenizers.
+1 -1
View File
@@ -82,7 +82,7 @@ Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this do
- **The location of the indexed text in your database schema.** Only FTS4 and FTS5 support "contentless" and "external content" tables.
- See [FST3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
- See [FTS3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
> **Note**: In case you were still wondering, it is recommended to read the SQLite documentation: [FTS3 & FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html).
+91 -45
View File
@@ -4,24 +4,32 @@ Migrating From GRDB 6 to GRDB 7
**This guide helps you upgrade your applications from GRDB 6 to GRDB 7.**
- [Preparing the Migration to GRDB 7](#preparing-the-migration-to-grdb-7)
- [Recommendations Regarding Swift Concurrency](#recommendations-regarding-swift-concurrency)
- [New requirements](#new-requirements)
- [The Record Base Class is Discouraged](#the-record-base-class-is-discouraged)
- [Companion Libraries](#companion-libraries)
- [Column Coding Strategies](#column-coding-strategies)
- [Cancellable Async Database Accesses](#cancellable-async-database-accesses)
- [Default Transaction Kind](#default-transaction-kind)
- [ValueObservation and the Main Actor](#valueobservation-and-the-main-actor)
- [Access to SQLite C functions](#access-to-sqlite-c-functions)
- [Recommendations Regarding Swift Concurrency](#recommendations-regarding-swift-concurrency)
- [The Record Base Class is Discouraged](#the-record-base-class-is-discouraged)
- [Other Changes](#other-changes)
## Preparing the Migration to GRDB 7
Before upgrading, ensure you are using the [latest GRDB 6 release](https://github.com/groue/GRDB.swift/tags) and address any deprecation warnings. Once this is done, proceed with upgrading to GRDB 7. Due to breaking changes, your application may no longer compile. Follow the fix-it suggestions for simple syntax updates, and review the specific modifications described below.
## Recommendations Regarding Swift Concurrency
GRDB 7 requires Xcode 16+ and a Swift 6 compiler.
Depending of the language mode and level of concurrency checkings used by your application, you may see warnings or errors. See [Migrating to Swift 6] on swift.org for more information about Swift 6. See [Swift Concurrency and GRDB] for GRDB-focused advice.
## New requirements
GRDB requirements have been bumped:
- **Swift Compiler 6+** (was Swift 5.7+). Both Swift 5 and Swift 6 language modes are supported. For more information, see the [Migrating to Swift 6] Apple guide.
- **Swift Compiler 6+** (was Swift 5.7+).
- **Xcode 16.0+** (was Xcode 14.0+)
- **iOS 13+** (was iOS 11+)
- **macOS 10.15+** (was macOS 10.13+)
@@ -29,41 +37,12 @@ GRDB requirements have been bumped:
- **watchOS 7.0+** (was watchOS 4+)
- **SQLite 3.20.0+** (was SQLite 3.19.3+)
## The Record Base Class is Discouraged
## Companion Libraries
The usage of the [Record] base class is **discouraged** in GRDB 7. Present in GRDB 1.0, in 2017, it has served its purpose.
Companion libraries have been updated for GRDB 7:
It is not recommended to define any new type that subclass `Record`.
It is recommended to refactor `Record` subclasses into Swift structs, before you enable the strict concurrency checkings or the Swift 6 language mode. See [Migrating to Swift 6] for more information about Swift 6 language modes.
For example:
```swift
// GRDB 6
class Player: Record {
var id: UUID
var name: String
var score: Int
override class var databaseTableName: String { "player" }
init(id: UUID, name: String, score: Int) { ... }
required init(row: Row) throws { ... }
override func encode(to container: inout PersistenceContainer) throws { ...}
}
// GRDB 7
struct Player: Codable {
var id: UUID
var name: String
var score: Int
}
extension Player: FetchableRecord, PersistableRecord { }
```
Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non-Sendable record types in GRDB.
- [GRDBQuery releases](https://github.com/groue/GRDBQuery/releases) (SwiftUI)
- [GRDBSnapshotTesting releases](https://github.com/groue/GRDBSnapshotTesting/releases) (Snapshot Testing)
## Column Coding Strategies
@@ -131,6 +110,46 @@ In GRDB 7, `Configuration` no longer has a `defaultTransactionKind` property, be
You can still specify a transaction kind explicitly when necessary. See [Transaction Kinds] for details.
## ValueObservation and the Main Actor
In GRDB 7, `ValueObservation` fosters the main actor, because it is frequently used to automatically update database values on screen.
By default, its [`start`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be started on the main actor, and its notification callbacks run on the main actor as well.
It is not necessary to call `MainActor.assumeIsolated` in `ValueObservation` callbacks:
```swift
// GRDB 7
@MainActor func startObservation() {
let observation = ValueObservation.tracking { ... }
let cancellable = observation.start(in: dbQueue) { error in
// This closure is MainActor-isolated.
} onChange: { value in
// This closure is MainActor-isolated.
print("Fresh value", value)
}
}
```
You can opt-out of the main actor with a specific scheduler such as `.async(onQueue:)`:
```swift
func startObservation() {
let observation = ValueObservation.tracking { ... }
let cancellable = observation.start(
in: dbQueue,
scheduling: .async(onQueue: .main))
{ error in
// Called on the specified dispatch queue.
} onChange: { value in
// Called on the specified dispatch queue.
print("Fresh value", value)
}
}
```
## Access to SQLite C functions
In GRDB 6, the underlying C SQLite library is implicitly available:
@@ -164,17 +183,44 @@ In GRDB 7, you may need an additional import, depending on how GRDB is integrate
- In other cases, no additional import is needed.
## Recommendations Regarding Swift Concurrency
## The Record Base Class is Discouraged
GRDB 7 requires Xcode 16+ and a Swift 6 compiler.
Subclassing the [Record] class is **discouraged** in GRDB 7. Present in GRDB 1.0, in 2017, it has served its purpose.
Depending of the language mode and level of concurrency checkings used by your application (see [Migrating to Swift 6]), you may see warnings or errors. We address those issues, and provide general guidance, in [Swift Concurrency and GRDB].
It is not recommended to define any new type that subclass `Record`.
It is recommended to refactor `Record` subclasses into Swift structs, before you enable the strict concurrency checkings or the Swift 6 language mode. See [Migrating to Swift 6] for more information about Swift 6 language modes.
For example:
```swift
// GRDB 6
class Player: Record {
var id: UUID
var name: String
var score: Int
override class var databaseTableName: String { "player" }
init(id: UUID, name: String, score: Int) { ... }
required init(row: Row) throws { ... }
override func encode(to container: inout PersistenceContainer) throws { ...}
}
// GRDB 7
struct Player: Codable {
var id: UUID
var name: String
var score: Int
}
extension Player: FetchableRecord, PersistableRecord { }
```
Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non-Sendable record types in GRDB.
## Other Changes
- `ValueObservation` must be started from the Main Actor by default. Use an explicit `async(onQueue: .main)` scheduling in order to remove this constraint.
- `DatabasePool.concurrentRead` has been removed. Use [`asyncConcurrentRead`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasepool/asyncconcurrentread(_:)) instead.
- The `PersistenceContainer` subscript no longer guarantees that the value returned is the same as what was previously set. It only guarantees that both values are encoded identically in the database.
@@ -182,7 +228,7 @@ Depending of the language mode and level of concurrency checkings used by your a
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/grdb.swiftdocumentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide
[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databasesharing
[Transaction Kinds]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactions#Transaction-Kinds
[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/swiftconcurrency
[Record]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/record
[Sharing a Database]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databasesharing
[Transaction Kinds]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/transactions#Transaction-Kinds
[Swift Concurrency and GRDB]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/swiftconcurrency
[Record]: https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/record
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '7.0.0-beta'
s.version = '7.0.0-beta.6'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
+3
View File
@@ -7,6 +7,9 @@ import SQLCipher
import SQLite3
#endif
#if !canImport(Darwin)
@preconcurrency
#endif
import Dispatch
import Foundation
+138 -21
View File
@@ -96,7 +96,15 @@ extension Database {
// MARK: - Database Schema
/// Returns the current schema version.
/// Returns the current schema version (`PRAGMA schema_version`).
///
/// For example:
///
/// ```swift
/// let version = try dbQueue.read { db in
/// try db.schemaVersion()
/// }
/// ```
///
/// Related SQLite documentation: <https://www.sqlite.org/pragma.html#pragma_schema_version>
public func schemaVersion() throws -> Int32 {
@@ -234,8 +242,19 @@ extension Database {
/// Returns whether a table exists
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
/// When `schemaName` is not specified, the result is true if any known
/// schema contains the table.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// if try db.tableExists("player") { ... }
/// if try db.tableExists("player", in: "main") { ... }
/// if try db.tableExists("player", in: "temp") { ... }
/// if try db.tableExists("player", in: "attached") { ... }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
@@ -278,8 +297,19 @@ extension Database {
/// Returns whether a view exists, in the main or temp schema, or in an
/// attached database.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
/// When `schemaName` is not specified, the result is true if any known
/// schema contains the table.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// if try db.viewExists("player") { ... }
/// if try db.viewExists("player", in: "main") { ... }
/// if try db.viewExists("player", in: "temp") { ... }
/// if try db.viewExists("player", in: "attached") { ... }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
@@ -296,8 +326,19 @@ extension Database {
/// Returns whether a trigger exists, in the main or temp schema, or in an
/// attached database.
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
/// When `schemaName` is not specified, the result is true if any known
/// schema contains the table.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// if try db.triggerExists("on_player_update") { ... }
/// if try db.triggerExists("on_player_update", in: "main") { ... }
/// if try db.triggerExists("on_player_update", in: "temp") { ... }
/// if try db.triggerExists("on_player_update", in: "attached") { ... }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or
/// if the specified schema does not exist
@@ -340,6 +381,15 @@ extension Database {
/// table has no explicit primary key, the result is the hidden
/// "rowid" column.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let primaryKey = try db.primaryKey("player")
/// print(primaryKey.columns)
/// }
/// ```
///
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
@@ -359,6 +409,36 @@ extension Database {
throw DatabaseError.noSuchTable(tableName)
}
/// Returns the name of the single-column primary key.
///
/// A fatal error is raised if the primary key has several columns, or
/// if `tableName` is the name of a database view.
func filteringPrimaryKeyColumn(_ tableName: String) throws -> String {
do {
let primaryKey = try primaryKey(tableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Filtering by primary key requires a single-column primary key in the table '\(tableName)'")
return primaryKey.columns[0]
} catch let error as DatabaseError {
// Maybe the user tries to filter a view by primary key,
// as in <https://github.com/groue/GRDB.swift/issues/1648>.
// In this case, raise a fatalError because this is a
// programmer error which is very likely to be detected
// during development.
if case .SQLITE_ERROR = error.resultCode,
(try? viewExists(tableName)) == true
{
fatalError("""
Filtering by primary key is not available on the database view '\(tableName)'. \
Use `filter(Column("...") == value)` instead.
""")
} else {
throw error
}
}
}
/// Returns nil if table does not exist
private func primaryKey(_ table: TableIdentifier) throws -> PrimaryKeyInfo? {
SchedulingWatchdog.preconditionValidQueue(self)
@@ -499,14 +579,26 @@ extension Database {
/// The indexes on table named `tableName`.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let indexes = db.indexes(in: "player")
/// for index in indexes {
/// print(index.columns)
/// }
/// }
/// ```
///
/// Only indexes on columns are returned. Indexes on expressions are
/// not returned.
///
/// SQLite does not define any index for INTEGER PRIMARY KEY columns: this
/// method does not return any index that represents the primary key.
/// SQLite does not define any index for INTEGER PRIMARY KEY columns:
/// this method does not return any index that represents the
/// primary key.
///
/// If you want to know if a set of columns uniquely identifies a row, because
/// the columns contain the primary key or a unique index, use
/// If you want to know if a set of columns uniquely identifies a row,
/// because the columns contain the primary key or a unique index, use
/// ``table(_:hasUniqueKey:)``.
///
/// When `schemaName` is not specified, known schemas are iterated in
@@ -587,16 +679,19 @@ extension Database {
/// For example:
///
/// ```swift
/// // One table with one primary key (id), and a unique index (a, b):
/// //
/// // > CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
/// // > CREATE UNIQUE INDEX i ON t(a, b);
/// try db.table("t", hasUniqueKey: ["id"]) // true
/// try db.table("t", hasUniqueKey: ["a", "b"]) // true
/// try db.table("t", hasUniqueKey: ["b", "a"]) // true
/// try db.table("t", hasUniqueKey: ["c"]) // false
/// try db.table("t", hasUniqueKey: ["id", "a"]) // true
/// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true
/// try dbQueue.read { db in
/// // One table with one primary key (id)
/// // and a unique index (a, b):
/// //
/// // > CREATE TABLE t(id INTEGER PRIMARY KEY, a, b, c);
/// // > CREATE UNIQUE INDEX i ON t(a, b);
/// try db.table("t", hasUniqueKey: ["id"]) // true
/// try db.table("t", hasUniqueKey: ["a", "b"]) // true
/// try db.table("t", hasUniqueKey: ["b", "a"]) // true
/// try db.table("t", hasUniqueKey: ["c"]) // false
/// try db.table("t", hasUniqueKey: ["id", "a"]) // true
/// try db.table("t", hasUniqueKey: ["id", "a", "b", "c"]) // true
/// }
/// ```
public func table(
_ tableName: String,
@@ -610,6 +705,17 @@ extension Database {
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let foreignKeys = try db.foreignKeys(in: "player")
/// for foreignKey in foreignKeys {
/// print(foreignKey.destinationTable)
/// }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist, or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
@@ -831,6 +937,17 @@ extension Database {
/// When `schemaName` is not specified, known schemas are iterated in
/// SQLite resolution order and the first matching result is returned.
///
/// For example:
///
/// ```swift
/// try dbQueue.read { db in
/// let columns = try db.columns(in: "player")
/// for column in columns {
/// print(column.name)
/// }
/// }
/// ```
///
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, if
/// the specified schema does not exist,or if no such table or view
/// with this name exists in the main or temp schema, or in an attached
+49
View File
@@ -60,6 +60,8 @@ import Foundation
/// - ``subscript(_:)-3tp8o``
/// - ``subscript(_:)-4k8od``
/// - ``subscript(_:)-9rbo7``
/// - ``coalesce(_:)-359k7``
/// - ``coalesce(_:)-6nbah``
/// - ``withUnsafeData(named:_:)``
/// - ``dataNoCopy(named:)``
///
@@ -671,6 +673,53 @@ extension Row {
public func dataNoCopy(_ column: some ColumnExpression) -> Data? {
dataNoCopy(named: column.name)
}
/// Returns the first non-null value, if any. Identical to SQL `COALESCE` function.
///
/// For example:
///
/// ```swift
/// let name: String? = row.coalesce(["nickname", "name"])
/// ```
///
/// Prefer `coalesce` to nil-coalescing row values, which does not
/// return the expected value:
///
/// ```swift
/// // INCORRECT
/// let name: String? = row["nickname"] ?? row["name"]
/// ```
public func coalesce<T: DatabaseValueConvertible>(
_ columns: some Collection<String>
) -> T? {
for column in columns {
if let value = self[column] as T? {
return value
}
}
return nil
}
/// Returns the first non-null value, if any. Identical to SQL `COALESCE` function.
///
/// For example:
///
/// ```swift
/// let name: String? = row.coalesce([Column("nickname"), Column("name")])
/// ```
///
/// Prefer `coalesce` to nil-coalescing row values, which does not
/// return the expected value:
///
/// ```swift
/// // INCORRECT
/// let name: String? = row[Column("nickname")] ?? row[Column("name")]
/// ```
public func coalesce<T: DatabaseValueConvertible>(
_ columns: some Collection<any ColumnExpression>
) -> T? {
return coalesce(columns.lazy.map { $0.name })
}
}
extension Row {
+3
View File
@@ -1,3 +1,6 @@
#if !canImport(Darwin)
@preconcurrency
#endif
import Dispatch
/// SchedulingWatchdog makes sure that databases connections are used on correct
+2
View File
@@ -13,6 +13,8 @@ import string_h
import Glibc
#elseif os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(visionOS)
import Darwin
#elseif os(Windows)
import ucrt
#endif
/// `StatementAuthorizer` provides information about compiled database
+1 -1
View File
@@ -1,4 +1,4 @@
#if !os(Linux)
#if !os(Linux) && !os(Windows)
import Foundation
private let integerRoundingBehavior = NSDecimalNumberHandler(
+1 -1
View File
@@ -1,6 +1,6 @@
import Foundation
#if !os(Linux)
#if !os(Linux) && !os(Windows)
/// NSURL stores its absoluteString in the database.
extension NSURL: DatabaseValueConvertible {
+1 -1
View File
@@ -9,7 +9,7 @@ import SQLite3
import Foundation
#if !os(Linux)
#if !os(Linux) && !os(Windows)
/// NSUUID adopts DatabaseValueConvertible
extension NSUUID: DatabaseValueConvertible {
/// Returns a BLOB database value containing the uuid bytes.
+10 -4
View File
@@ -4,11 +4,17 @@ GRDB helps your app deal with Swift and SQLite concurrency.
## Overview
If your app moves slow database jobs off the main thread, so that the user interface remains responsive, then this guide is for you. In the case of apps that share a database with other processes, such as an iOS app and its extensions, don't miss the dedicated <doc:DatabaseSharing> guide after this one.
If your app moves slow database jobs off the main thread, so that the user interface remains responsive, then this guide is for you.
**In all cases, and first and foremost, follow the <doc:Concurrency#Concurrency-Rules> right from the start.**
It is extended with three articles that focus on particular aspects of concurrency:
The other chapters cover, with more details, the fundamentals of SQLite concurrency, and how GRDB makes it manageable from your Swift code.
- <doc:DatabaseSharing>: for apps that **share a database** with other processes, such as an iOS app and its extensions
- <doc:SwiftConcurrency>: the relationships between GRDB and **Swift 6 Concurrency**
- <doc:MainThread>: everything you have to known about GRDB and the main thread.
**In all cases, and first and foremost, follow the Concurrency-Rules, below, right from the start.**
The following chapters cover the fundamentals of SQLite concurrency, and how GRDB makes it manageable from your Swift code.
## Concurrency Rules
@@ -322,7 +328,7 @@ Types that conform to ``TransactionObserver`` can also use those methods in thei
- <doc:SwiftConcurrency>
- <doc:DatabaseSharing>
- <doc:MainThread>
[demo apps]: https://github.com/groue/GRDB.swift/tree/master/Documentation/DemoApps
[`SQLITE_BUSY`]: https://www.sqlite.org/rescode.html#busy
+9 -398
View File
@@ -6,7 +6,7 @@ Define or query the database schema.
**GRDB supports all database schemas, and has no requirement.** Any existing SQLite database can be opened, and you are free to structure your new databases as you wish.
You perform modifications to the database schema with methods such as ``Database/create(table:options:body:)``, listed at the end of this page. For example:
You perform modifications to the database schema with methods such as ``Database/create(table:options:body:)``, listed in <doc:DatabaseSchemaModifications>. For example:
```swift
try db.create(table: "player") { t in
@@ -16,408 +16,19 @@ try db.create(table: "player") { t in
}
```
When you plan to evolve the schema as new versions of your application ship, wrap all schema changes in <doc:Migrations>.
Prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example).
When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See <doc:Migrations> for the detailed procedure.
## Database Schema Recommendations
Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
For recommendations specific to JSON columns, see <doc:JSON>.
### Table names should be English, singular, and camelCased
Make them look like singular Swift identifiers: `player`, `team`, `postalAddress`:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
// table columns and constraints
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "players") { t in
// table columns and constraints
}
```
☝️ **If table names follow a different naming convention**, record types (see <doc:QueryInterface>) will need explicit table names:
```swift
extension Player: TableRecord {
// Required because table name is not 'player'
static let databaseTableName = "players"
}
extension PostalAddress: TableRecord {
// Required because table name is not 'postalAddress'
static let databaseTableName = "postal_address"
}
extension Award: TableRecord {
// Required because table name is not 'award'
static let databaseTableName = "Auszeichnung"
}
```
[Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) will need explicit keys as well:
```swift
extension Player: TableRecord {
// Explicit association key because the table name is not 'postalAddress'
static let postalAddress = belongsTo(PostalAddress.self, key: "postalAddress")
// Explicit association key because the table name is not 'award'
static let awards = hasMany(Award.self, key: "awards")
}
```
As in the above example, make sure to-one associations use singular keys, and to-many associations use plural keys.
### Column names should be camelCased
Again, make them look like Swift identifiers: `fullName`, `score`, `creationDate`:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("fullName", .text).notNull()
t.column("score", .integer).notNull()
t.column("creationDate", .datetime).notNull()
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("full_name", .text).notNull()
t.column("score", .integer).notNull()
t.column("creation_date", .datetime).notNull()
}
```
☝️ **If the column names follow a different naming convention**, `Codable` record types will need an explicit `CodingKeys` enum:
```swift
struct Player: Decodable, FetchableRecord {
var id: Int64
var fullName: String
var score: Int
var creationDate: Date
// Required CodingKeys customization because
// columns are not named like Swift properties
enum CodingKeys: String, CodingKey {
case id, fullName = "full_name", score, creationDate = "creation_date"
}
}
```
### Tables should have explicit primary keys
A primary key uniquely identifies a row in a table. It is defined on one or several columns:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
// Auto-incremented primary key
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.create(table: "team") { t in
// Single-column primary key
t.primaryKey("id", .text)
t.column("name", .text).notNull()
}
try db.create(table: "membership") { t in
// Composite primary key
t.primaryKey {
t.belongsTo("player")
t.belongsTo("team")
}
t.column("role", .text).notNull()
}
```
Primary keys support record fetching methods such as ``FetchableRecord/fetchOne(_:id:)``, and persistence methods such as ``MutablePersistableRecord/update(_:onConflict:)`` or ``MutablePersistableRecord/delete(_:)``.
See <doc:SingleRowTables> when you need to define a table that contains a single row.
☝️ **If the database table does not define any explicit primary key**, identifying specific rows in this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html) in the matching record types:
```swift
// A table without any explicit primary key
try db.create(table: "player") { t in
t.column("name", .text).notNull()
t.column("score", .integer).notNull()
}
// The record type for the 'player' table'
struct Player: Codable {
// Uniquely identifies a player.
var rowid: Int64?
var name: String
var score: Int
}
extension Player: FetchableRecord, MutablePersistableRecord {
// Required because the primary key
// is the hidden rowid column.
static var databaseSelection: [any SQLSelectable] {
[AllColumns(), Column.rowID]
}
// Update id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
rowid = inserted.rowID
}
}
try dbQueue.read { db in
// SELECT *, rowid FROM player WHERE rowid = 1
if let player = try Player.fetchOne(db, id: 1) {
// DELETE FROM player WHERE rowid = 1
let deleted = try player.delete(db)
print(deleted) // true
}
}
```
### Single-column primary keys should be named 'id'
This helps record types play well with the standard `Identifiable` protocol.
```swift
// RECOMMENDED
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "player") { t in
t.primaryKey("uuid", .text)
t.column("name", .text).notNull()
}
```
☝️ **If the primary key follows a different naming convention**, `Identifiable` record types will need a custom `CodingKeys` enum, or an extra property:
```swift
// Custom coding keys
struct Player: Codable, Identifiable {
var id: String
var name: String
// Required CodingKeys customization because
// columns are not named like Swift properties
enum CodingKeys: String, CodingKey {
case id = "uuid", name
}
}
// Extra property
struct Player: Identifiable {
var uuid: String
var name: String
// Required because the primary key column is not 'id'
var id: String { uuid }
}
```
### Unique keys should be supported by unique indexes
Unique indexes makes sure SQLite prevents the insertion of conflicting rows:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("team").notNull()
t.column("position", .integer).notNull()
// Players must have distinct names
t.column("name", .text).unique()
}
// One single player at any given position in a team
try db.create(
indexOn: "player",
columns: ["teamId", "position"],
options: .unique)
```
> Tip: SQLite does not support deferred unique indexes, and this creates undesired churn when you need to temporarily break them. This may happen, for example, when you want to reorder player positions in our above example.
>
> There exist several workarounds; one of them involves dropping and recreating the unique index after the temporary violations have been fixed. If you plan to use this technique, take care that only actual indexes can be dropped. Unique constraints created inside the table body can not:
>
> ```swift
> // Unique constraint on player(name) can not be dropped.
> try db.create(table: "player") { t in
> t.column("name", .text).unique()
> }
>
> // Unique index on team(name) can be dropped.
> try db.create(table: "team") { t in
> t.column("name", .text)
> }
> try db.create(indexOn: "team", columns: ["name"], options: .unique)
> ```
>
> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See <doc:Migrations> for the detailed procedure.
☝️ **If a table misses unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error:
```swift
try dbQueue.write { db in
// Fatal error: table player has no unique index on columns ...
let player = try Player.fetchOne(db, key: ["teamId": 42, "position": 1])
try Player.deleteOne(db, key: ["name": "Arthur"])
// Use instead:
let player = try Player
.filter(Column("teamId") == 42 && Column("position") == 1)
.fetchOne(db)
try Player
.filter(Column("name") == "Arthur")
.deleteAll(db)
}
```
### Relations between tables should be supported by foreign keys
[Foreign Keys](https://www.sqlite.org/foreignkeys.html) have SQLite enforce valid relationships between tables:
```swift
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("id")
t.column("color", .text).notNull()
}
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// A player must refer to an existing team
t.belongsTo("team").notNull()
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// No foreign key
t.column("teamId", .integer).notNull()
}
```
See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`` for more information about the creation of foreign keys.
GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema:
```swift
extension Player: TableRecord {
static let team = belongsTo(Team.self)
}
extension Team: TableRecord {
static let players = hasMany(Player.self)
}
```
See [Associations and the Database Schema](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#associations-and-the-database-schema) for more precise recommendations.
☝️ **If a foreign key is not declared in the schema**, you will need to explicitly configure related associations:
```swift
extension Player: TableRecord {
// Required configuration because the database does
// not declare any foreign key from players to their team.
static let teamForeignKey = ForeignKey(["teamId"])
static let team = belongsTo(Team.self,
using: teamForeignKey)
}
extension Team: TableRecord {
// Required configuration because the database does
// not declare any foreign key from players to their team.
static let players = hasMany(Player.self,
using: Player.teamForeignKey)
}
```
Most applications modify the database schema as new versions ship: it is recommended to wrap all schema changes in <doc:Migrations>.
## Topics
### Database Tables
### Define the database schema
- ``Database/alter(table:body:)``
- ``Database/create(table:options:body:)``
- ``Database/create(virtualTable:ifNotExists:using:)``
- ``Database/create(virtualTable:ifNotExists:using:_:)``
- ``Database/drop(table:)``
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
- ``Database/rename(table:to:)``
- ``Database/ColumnType``
- ``Database/ConflictResolution``
- ``Database/ForeignKeyAction``
- ``TableAlteration``
- ``TableDefinition``
- ``TableOptions``
- ``VirtualTableModule``
- <doc:DatabaseSchemaModifications>
- <doc:DatabaseSchemaRecommendations>
### Database Views
### Introspect the database schema
- ``Database/create(view:options:columns:as:)``
- ``Database/create(view:options:columns:asLiteral:)``
- ``Database/drop(view:)``
- ``ViewOptions``
- <doc:DatabaseSchemaIntrospection>
### Database Indexes
### Check the database schema
- ``Database/create(indexOn:columns:options:condition:)``
- ``Database/create(index:on:columns:options:condition:)``
- ``Database/create(index:on:expressions:options:condition:)``
- ``Database/drop(indexOn:columns:)``
- ``Database/drop(index:)``
- ``IndexOptions``
### Querying the Database Schema
- ``Database/columns(in:in:)``
- ``Database/foreignKeys(on:in:)``
- ``Database/indexes(on:in:)``
- ``Database/isGRDBInternalTable(_:)``
- ``Database/isSQLiteInternalTable(_:)``
- ``Database/primaryKey(_:in:)``
- ``Database/schemaVersion()``
- ``Database/table(_:hasUniqueKey:)``
- ``Database/tableExists(_:in:)``
- ``Database/triggerExists(_:in:)``
- ``Database/viewExists(_:in:)``
- ``ColumnInfo``
- ``ForeignKeyInfo``
- ``IndexInfo``
- ``PrimaryKeyInfo``
### Integrity Checks
- ``Database/checkForeignKeys()``
- ``Database/checkForeignKeys(in:in:)``
- ``Database/foreignKeyViolations()``
- ``Database/foreignKeyViolations(in:in:)``
- ``ForeignKeyViolation``
### Sunsetted Methods
Those are legacy interfaces that are preserved for backwards compatibility. Their use is not recommended.
- ``Database/create(index:on:columns:unique:ifNotExists:condition:)``
- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)``
- <doc:DatabaseSchemaIntegrityChecks>
@@ -0,0 +1,13 @@
# Integrity Checks
Perform integrity checks of the database content
## Topics
### Integrity Checks
- ``Database/checkForeignKeys()``
- ``Database/checkForeignKeys(in:in:)``
- ``Database/foreignKeyViolations()``
- ``Database/foreignKeyViolations(in:in:)``
- ``ForeignKeyViolation``
@@ -0,0 +1,35 @@
# Database Schema Introspection
Get information about schema objects such as tables, columns, indexes, foreign keys, etc.
## Topics
### Querying the Schema Version
- ``Database/schemaVersion()``
### Existence Checks
- ``Database/tableExists(_:in:)``
- ``Database/triggerExists(_:in:)``
- ``Database/viewExists(_:in:)``
### Table Structure
- ``Database/columns(in:in:)``
- ``Database/foreignKeys(on:in:)``
- ``Database/indexes(on:in:)``
- ``Database/primaryKey(_:in:)``
- ``Database/table(_:hasUniqueKey:)``
### Reserved Tables
- ``Database/isGRDBInternalTable(_:)``
- ``Database/isSQLiteInternalTable(_:)``
### Supporting Types
- ``ColumnInfo``
- ``ForeignKeyInfo``
- ``IndexInfo``
- ``PrimaryKeyInfo``
@@ -0,0 +1,290 @@
# Modifying the Database Schema
How to modify the database schema
## Overview
For modifying the database schema, prefer Swift methods over raw SQL queries. They allow the compiler to check if a schema change is available on the target operating system. Only use a raw SQL query when no Swift method exist (when creating triggers, for example).
When a schema change is not directly supported by SQLite, or not available on the target operating system, database tables have to be recreated. See <doc:Migrations> for the detailed procedure.
## Create Tables
The ``Database/create(table:options:body:)`` method covers nearly all SQLite table creation features. For virtual tables, see [Full-Text Search](https://github.com/groue/GRDB.swift/blob/master/Documentation/FullTextSearch.md), or use raw SQL.
```swift
// CREATE TABLE place (
// id INTEGER PRIMARY KEY AUTOINCREMENT,
// title TEXT,
// favorite BOOLEAN NOT NULL DEFAULT 0,
// latitude DOUBLE NOT NULL,
// longitude DOUBLE NOT NULL
// )
try db.create(table: "place") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text)
t.column("favorite", .boolean).notNull().defaults(to: false)
t.column("longitude", .double).notNull()
t.column("latitude", .double).notNull()
}
```
**Configure table creation**
```swift
// CREATE TABLE player ( ... )
try db.create(table: "player") { t in ... }
// CREATE TEMPORARY TABLE player IF NOT EXISTS (
try db.create(table: "player", options: [.temporary, .ifNotExists]) { t in ... }
```
Reference: ``TableOptions``
**Add regular columns** with their name and eventual type (`text`, `integer`, `double`, `real`, `numeric`, `boolean`, `blob`, `date`, `datetime`, `any`, and `json`) - see [SQLite data types](https://www.sqlite.org/datatype3.html) and <doc:JSON>:
```swift
// CREATE TABLE player (
// score,
// name TEXT,
// creationDate DATETIME,
// address TEXT,
try db.create(table: "player") { t in
t.column("score")
t.column("name", .text)
t.column("creationDate", .datetime)
t.column("address", .json)
```
Reference: ``TableDefinition/column(_:_:)``
Define **not null** columns, and set **default values**:
```swift
// email TEXT NOT NULL,
t.column("email", .text).notNull()
// name TEXT NOT NULL DEFAULT 'Anonymous',
t.column("name", .text).notNull().defaults(to: "Anonymous")
```
Reference: ``ColumnDefinition``
**Define primary, unique, or foreign keys**. When defining a foreign key, the referenced column is the primary key of the referenced table (unless you specify otherwise):
```swift
// id INTEGER PRIMARY KEY AUTOINCREMENT,
t.autoIncrementedPrimaryKey("id")
// uuid TEXT PRIMARY KEY NOT NULL,
t.primaryKey("uuid", .text)
// teamName TEXT NOT NULL,
// position INTEGER NOT NULL,
// PRIMARY KEY (teamName, position),
t.primaryKey {
t.column("teamName", .text)
t.column("position", .integer)
}
// email TEXT UNIQUE,
t.column("email", .text).unique()
// teamId TEXT REFERENCES team(id) ON DELETE CASCADE,
// countryCode TEXT REFERENCES country(code) NOT NULL,
t.belongsTo("team", onDelete: .cascade)
t.belongsTo("country").notNull()
```
Reference: ``TableDefinition``, ``ColumnDefinition/unique(onConflict:)``
**Create an index** on a column
```swift
t.column("score", .integer).indexed()
```
Reference: ``ColumnDefinition``
For extra index options, see <doc:DatabaseSchemaModifications#Create-Indexes> below.
**Perform integrity checks** on individual columns, and SQLite will only let conforming rows in. In the example below, the `$0` closure variable is a column which lets you build any SQL expression.
```swift
// name TEXT CHECK (LENGTH(name) > 0)
// score INTEGER CHECK (score > 0)
t.column("name", .text).check { length($0) > 0 }
t.column("score", .integer).check(sql: "score > 0")
```
Reference: ``ColumnDefinition``
Columns can also be defined with a raw sql String, or an [SQL literal](https://github.com/groue/GRDB.swift/blob/master/Documentation/SQLInterpolation.md#sql-literal) in which you can safely embed raw values without any risk of syntax errors or SQL injection:
```swift
t.column(sql: "name TEXT")
let defaultName: String = ...
t.column(literal: "name TEXT DEFAULT \(defaultName)")
```
Reference: ``TableDefinition``
Other **table constraints** can involve several columns:
```swift
// PRIMARY KEY (a, b),
t.primaryKey(["a", "b"])
// UNIQUE (a, b) ON CONFLICT REPLACE,
t.uniqueKey(["a", "b"], onConflict: .replace)
// FOREIGN KEY (a, b) REFERENCES parents(c, d),
t.foreignKey(["a", "b"], references: "parents")
// CHECK (a + b < 10),
t.check(Column("a") + Column("b") < 10)
// CHECK (a + b < 10)
t.check(sql: "a + b < 10")
// Raw SQL constraints
t.constraint(sql: "CHECK (a + b < 10)")
t.constraint(literal: "CHECK (a + b < \(10))")
```
Reference: ``TableDefinition``
**Generated columns**:
```swift
t.column("totalScore", .integer).generatedAs(sql: "score + bonus")
t.column("totalScore", .integer).generatedAs(Column("score") + Column("bonus"))
}
```
Reference: ``ColumnDefinition``
## Modify Tables
SQLite lets you modify existing tables:
```swift
// ALTER TABLE referer RENAME TO referrer
try db.rename(table: "referer", to: "referrer")
// ALTER TABLE player ADD COLUMN hasBonus BOOLEAN
// ALTER TABLE player RENAME COLUMN url TO homeURL
// ALTER TABLE player DROP COLUMN score
try db.alter(table: "player") { t in
t.add(column: "hasBonus", .boolean)
t.rename(column: "url", to: "homeURL")
t.drop(column: "score")
}
```
Reference: ``TableAlteration``
> Note: SQLite restricts the possible table alterations, and may require you to recreate dependent triggers or views. See <doc:Migrations#Defining-the-Database-Schema-from-a-Migration> for more information.
## Drop Tables
Drop tables with the ``Database/drop(table:)`` method:
```swift
try db.drop(table: "obsolete")
```
## Create Indexes
Create an index on a column:
```swift
try db.create(table: "player") { t in
t.column("email", .text).unique()
t.column("score", .integer).indexed()
}
```
Create indexes on an existing table:
```swift
// CREATE INDEX index_player_on_email ON player(email)
try db.create(indexOn: "player", columns: ["email"])
// CREATE UNIQUE INDEX index_player_on_email ON player(email)
try db.create(indexOn: "player", columns: ["email"], options: .unique)
```
Create indexes with a specific collation:
```swift
// CREATE INDEX index_player_on_email ON player(email COLLATE NOCASE)
try db.create(
index: "index_player_on_email",
on: "player",
expressions: [Column("email").collating(.nocase)])
```
Create indexes on expressions:
```swift
// CREATE INDEX index_player_on_total_score ON player(score+bonus)
try db.create(
index: "index_player_on_total_score",
on: "player",
expressions: [Column("score") + Column("bonus")])
// CREATE INDEX index_player_on_country ON player(address ->> 'country')
try db.create(
index: "index_player_on_country",
on: "player",
expressions: [
JSONColumn("address")["country"],
])
```
Unique constraints and unique indexes are somewhat different: don't miss the tip in <doc:DatabaseSchemaRecommendations/Unique-keys-should-be-supported-by-unique-indexes> below.
## Topics
### Database Tables
- ``Database/alter(table:body:)``
- ``Database/create(table:options:body:)``
- ``Database/create(virtualTable:ifNotExists:using:)``
- ``Database/create(virtualTable:ifNotExists:using:_:)``
- ``Database/drop(table:)``
- ``Database/dropFTS4SynchronizationTriggers(forTable:)``
- ``Database/dropFTS5SynchronizationTriggers(forTable:)``
- ``Database/rename(table:to:)``
- ``Database/ColumnType``
- ``Database/ConflictResolution``
- ``Database/ForeignKeyAction``
- ``TableAlteration``
- ``TableDefinition``
- ``TableOptions``
- ``VirtualTableModule``
### Database Views
- ``Database/create(view:options:columns:as:)``
- ``Database/create(view:options:columns:asLiteral:)``
- ``Database/drop(view:)``
- ``ViewOptions``
### Database Indexes
- ``Database/create(indexOn:columns:options:condition:)``
- ``Database/create(index:on:columns:options:condition:)``
- ``Database/create(index:on:expressions:options:condition:)``
- ``Database/drop(indexOn:columns:)``
- ``Database/drop(index:)``
- ``IndexOptions``
### Sunsetted Methods
Those are legacy interfaces that are preserved for backwards compatibility. Their use is not recommended.
- ``Database/create(index:on:columns:unique:ifNotExists:condition:)``
- ``Database/create(table:temporary:ifNotExists:withoutRowID:body:)``
@@ -0,0 +1,334 @@
# Database Schema Recommendations
Recommendations for an ideal integration of the database schema with GRDB
## Overview
Even though all schema are supported, some features of the library and of the Swift language are easier to use when the schema follows a few conventions described below.
When those conventions are not applied, or not applicable, you will have to perform extra configurations.
For recommendations specific to JSON columns, see <doc:JSON>.
## Table names should be English, singular, and camelCased
Make them look like singular Swift identifiers: `player`, `team`, `postalAddress`:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
// table columns and constraints
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "players") { t in
// table columns and constraints
}
```
☝️ **If table names follow a different naming convention**, record types (see <doc:QueryInterface>) will need explicit table names:
```swift
extension Player: TableRecord {
// Required because table name is not 'player'
static let databaseTableName = "players"
}
extension PostalAddress: TableRecord {
// Required because table name is not 'postalAddress'
static let databaseTableName = "postal_address"
}
extension Award: TableRecord {
// Required because table name is not 'award'
static let databaseTableName = "Auszeichnung"
}
```
[Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) will need explicit keys as well:
```swift
extension Player: TableRecord {
// Explicit association key because the table name is not 'postalAddress'
static let postalAddress = belongsTo(PostalAddress.self, key: "postalAddress")
// Explicit association key because the table name is not 'award'
static let awards = hasMany(Award.self, key: "awards")
}
```
As in the above example, make sure to-one associations use singular keys, and to-many associations use plural keys.
## Column names should be camelCased
Again, make them look like Swift identifiers: `fullName`, `score`, `creationDate`:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("fullName", .text).notNull()
t.column("score", .integer).notNull()
t.column("creationDate", .datetime).notNull()
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("full_name", .text).notNull()
t.column("score", .integer).notNull()
t.column("creation_date", .datetime).notNull()
}
```
☝️ **If the column names follow a different naming convention**, `Codable` record types will need an explicit `CodingKeys` enum:
```swift
struct Player: Decodable, FetchableRecord {
var id: Int64
var fullName: String
var score: Int
var creationDate: Date
// Required CodingKeys customization because
// columns are not named like Swift properties
enum CodingKeys: String, CodingKey {
case id, fullName = "full_name", score, creationDate = "creation_date"
}
}
```
## Tables should have explicit primary keys
A primary key uniquely identifies a row in a table. It is defined on one or several columns:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
// Auto-incremented primary key
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
}
try db.create(table: "team") { t in
// Single-column primary key
t.primaryKey("id", .text)
t.column("name", .text).notNull()
}
try db.create(table: "membership") { t in
// Composite primary key
t.primaryKey {
t.belongsTo("player")
t.belongsTo("team")
}
t.column("role", .text).notNull()
}
```
Primary keys support record fetching methods such as ``FetchableRecord/fetchOne(_:id:)``, and persistence methods such as ``MutablePersistableRecord/update(_:onConflict:)`` or ``MutablePersistableRecord/delete(_:)``.
See <doc:SingleRowTables> when you need to define a table that contains a single row.
☝️ **If the database table does not define any explicit primary key**, identifying specific rows in this table needs explicit support for the [hidden `rowid` column](https://www.sqlite.org/rowidtable.html) in the matching record types:
```swift
// A table without any explicit primary key
try db.create(table: "player") { t in
t.column("name", .text).notNull()
t.column("score", .integer).notNull()
}
// The record type for the 'player' table'
struct Player: Codable {
// Uniquely identifies a player.
var rowid: Int64?
var name: String
var score: Int
}
extension Player: FetchableRecord, MutablePersistableRecord {
// Required because the primary key
// is the hidden rowid column.
static var databaseSelection: [any SQLSelectable] {
[AllColumns(), Column.rowID]
}
// Update id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
rowid = inserted.rowID
}
}
try dbQueue.read { db in
// SELECT *, rowid FROM player WHERE rowid = 1
if let player = try Player.fetchOne(db, id: 1) {
// DELETE FROM player WHERE rowid = 1
let deleted = try player.delete(db)
print(deleted) // true
}
}
```
## Single-column primary keys should be named 'id'
This helps record types play well with the standard `Identifiable` protocol.
```swift
// RECOMMENDED
try db.create(table: "player") { t in
t.primaryKey("id", .text)
t.column("name", .text).notNull()
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "player") { t in
t.primaryKey("uuid", .text)
t.column("name", .text).notNull()
}
```
☝️ **If the primary key follows a different naming convention**, `Identifiable` record types will need a custom `CodingKeys` enum, or an extra property:
```swift
// Custom coding keys
struct Player: Codable, Identifiable {
var id: String
var name: String
// Required CodingKeys customization because
// columns are not named like Swift properties
enum CodingKeys: String, CodingKey {
case id = "uuid", name
}
}
// Extra property
struct Player: Identifiable {
var uuid: String
var name: String
// Required because the primary key column is not 'id'
var id: String { uuid }
}
```
## Unique keys should be supported by unique indexes
Unique indexes makes sure SQLite prevents the insertion of conflicting rows:
```swift
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.belongsTo("team").notNull()
t.column("position", .integer).notNull()
// Players must have distinct names
t.column("name", .text).unique()
}
// One single player at any given position in a team
try db.create(
indexOn: "player",
columns: ["teamId", "position"],
options: .unique)
```
> Tip: SQLite does not support deferred unique indexes, and this creates undesired churn when you need to temporarily break them. This may happen, for example, when you want to reorder player positions in our above example.
>
> There exist several workarounds; one of them involves dropping and recreating the unique index after the temporary violations have been fixed. If you plan to use this technique, take care that only actual indexes can be dropped. Unique constraints created inside the table body can not:
>
> ```swift
> // Unique constraint on player(name) can not be dropped.
> try db.create(table: "player") { t in
> t.column("name", .text).unique()
> }
>
> // Unique index on team(name) can be dropped.
> try db.create(table: "team") { t in
> t.column("name", .text)
> }
> try db.create(indexOn: "team", columns: ["name"], options: .unique)
> ```
>
> If you want to turn an undroppable constraint into a droppable index, you'll need to recreate the database table. See <doc:Migrations> for the detailed procedure.
☝️ **If a table misses unique indexes**, some record methods such as ``FetchableRecord/fetchOne(_:key:)-92b9m`` and ``TableRecord/deleteOne(_:key:)-5pdh5`` will raise a fatal error:
```swift
try dbQueue.write { db in
// Fatal error: table player has no unique index on columns ...
let player = try Player.fetchOne(db, key: ["teamId": 42, "position": 1])
try Player.deleteOne(db, key: ["name": "Arthur"])
// Use instead:
let player = try Player
.filter(Column("teamId") == 42 && Column("position") == 1)
.fetchOne(db)
try Player
.filter(Column("name") == "Arthur")
.deleteAll(db)
}
```
## Relations between tables should be supported by foreign keys
[Foreign Keys](https://www.sqlite.org/foreignkeys.html) have SQLite enforce valid relationships between tables:
```swift
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("id")
t.column("color", .text).notNull()
}
// RECOMMENDED
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// A player must refer to an existing team
t.belongsTo("team").notNull()
}
// REQUIRES EXTRA CONFIGURATION
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
// No foreign key
t.column("teamId", .integer).notNull()
}
```
See ``TableDefinition/belongsTo(_:inTable:onDelete:onUpdate:deferred:indexed:)`` for more information about the creation of foreign keys.
GRDB [Associations](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md) are automatically configured from foreign keys declared in the database schema:
```swift
extension Player: TableRecord {
static let team = belongsTo(Team.self)
}
extension Team: TableRecord {
static let players = hasMany(Player.self)
}
```
See [Associations and the Database Schema](https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md#associations-and-the-database-schema) for more precise recommendations.
☝️ **If a foreign key is not declared in the schema**, you will need to explicitly configure related associations:
```swift
extension Player: TableRecord {
// Required configuration because the database does
// not declare any foreign key from players to their team.
static let teamForeignKey = ForeignKey(["teamId"])
static let team = belongsTo(Team.self,
using: teamForeignKey)
}
extension Team: TableRecord {
// Required configuration because the database does
// not declare any foreign key from players to their team.
static let players = hasMany(Player.self,
using: Player.teamForeignKey)
}
```
@@ -103,9 +103,9 @@ By default, `ValueObservation` notifies the initial value, as well as eventual c
```swift
// The default scheduling
let cancellable = observation.start(in: dbQueue) { error in
// Called asynchronously on the main actor
// This closure is MainActor-isolated.
} onChange: { value in
// Called asynchronously on the main actor
// This closure is MainActor-isolated.
print("Fresh value", value)
}
```
+18 -3
View File
@@ -27,8 +27,8 @@ try db.create(table: "player") { t in
> Tip: When an application performs queries on values embedded inside JSON columns, indexes can help performance:
>
> ```swift
> // CREATE INDEX "player_on_country"
> // ON "player"("address" ->> 'country')
> // CREATE INDEX player_on_country
> // ON player(address ->> 'country')
> try db.create(
> index: "player_on_country",
> on: "player",
@@ -37,7 +37,7 @@ try db.create(table: "player") { t in
> ])
>
> // SELECT * FROM player
> // WHERE "address" ->> 'country' = 'DE'
> // WHERE address ->> 'country' = 'DE'
> let germanPlayers = try Player
> .filter(JSONColumn("address")["country"] == "DE")
> .fetchAll(db)
@@ -98,6 +98,21 @@ extension Team: FetchableRecord, PersistableRecord {
}
```
> Tip: Conform your `Codable` property to `DatabaseValueConvertible` if you want to be able to filter on specific values of it:
>
> ```swift
> struct Address: Codable { ... }
> extension Address: DatabaseValueConvertible {}
>
> // SELECT * FROM player
> // WHERE address = '{"street": "...", "city": "...", "country": "..."}'
> let players = try Player
> .filter(JSONColumn("address") == Address(...))
> .fetchAll(db)
> ```
>
> Take care that SQLite will compare strings, not JSON objects: white-space and key ordering matter. For this comparison to succeed, make sure that the database contains values that are formatted exactly like a serialized `Address`.
## Manipulate JSON values at the database level
[SQLite JSON functions and operators](https://www.sqlite.org/json1.html) are available starting iOS 16+, macOS 10.15+, tvOS 17+, and watchOS 9+.
+30
View File
@@ -0,0 +1,30 @@
# Using or Avoiding the Main Thread
Everything you have to known about GRDB and the main thread.
## Overview
**This guide describes the relationship between GRDB and the main thread.** It complements the <doc:Concurrency> guide, that you should read first.
Accessing the database from the main thread is handy. Graphical applications, for example, do not need to show a loading screen until values are fetched and ready for display. They do not need to spawn tasks or any other asynchronous constructs in response to user actions.
There are only two things one should think about when accessing the database from the main thread:
- How long does it take to start the database access?
- How long does it take to execute the database requests?
The first delay depends on *database contention*
The first delay can be slowed down if the database is already busy
SQLite is very fast, and many database accesses are so fast that the user has no time to notice them. In a graphical application, performing fast database accesses from the main thread is handy, because the application does not need to show a loading screen until values are fetched and ready for display.
Other database accesses should be performed in a background thread, in order to avoid user interface freezes.
In the end, accessing the database on or off the main thread is a choice left to the application.
The database can be accessed from the main thread, or from a background thread, at the application convenience. In this guide we explain what you have to know when you intend to access the database from the main thread, or when you want to make sure a database access does not block the main thread. We will discuss plain database accesses (`read`, `write`), as well a database observation with ``ValueObservation``.
### Avoiding the Main Thread
To avoid performing database accesses from the main thread,
<!--@START_MENU_TOKEN@-->Text<!--@END_MENU_TOKEN@-->
@@ -39,7 +39,7 @@ migrator.registerMigration("createLibrary") { db in
try migrator.migrate(dbQueue)
```
1. Our database tables follow the <doc:DatabaseSchema#Database-Schema-Recommendations>: table names are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
1. Our database tables follow the <doc:DatabaseSchemaRecommendations>: table names are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
2. Each author has a unique id.
3. An author must have a name.
4. The country of an author is not always known.
+65 -92
View File
@@ -4,6 +4,8 @@ How to best integrate GRDB and Swift Concurrency
## Overview
**This guide describes the relationship between GRDB and Swift 6 Concurrency.** It complements the <doc:Concurrency> guide, that you should read first.
GRDB’s primary goal is to leverage SQLite’s concurrency features for the benefit of application developers. Swift 6 makes it possible to achieve this goal while ensuring data-race safety.
For example, the ``DatabasePool`` connection allows applications to fetch and display database values on screen, even while a background task is writing the results of a network request to disk.
@@ -39,11 +41,73 @@ All safety guarantees of Swift 6 are enforced during database accesses. They are
The following sections describe, with more details, how GRDB interacts with Swift Concurrency.
- <doc:SwiftConcurrency#Non-Sendable-Record-Types>
- <doc:SwiftConcurrency#Shorthand-Closure-Notation>
- <doc:SwiftConcurrency#Non-Sendable-Configuration-of-Record-Types>
- <doc:SwiftConcurrency#Non-Sendable-Record-Types>
- <doc:SwiftConcurrency#Choosing-between-Synchronous-and-Asynchronous-Database-Accesses>
### Shorthand Closure Notation
In the Swift 5 language mode, the compiler emits a warning when a database access is written with the shorthand closure notation:
```swift
// Standard closure:
let count = try await writer.read { db in
try Player.fetchCount(db)
}
// Shorthand notation:
// ⚠️ Converting non-sendable function value to '@Sendable (Database)
// throws -> Int' may introduce data races.
let count = try await writer.read(Player.fetchCount)
```
**You can remove this warning** by enabling [SE-0418: Inferring `Sendable` for methods and key path literals](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md), as below:
- **Using Xcode**
Set `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` to `YES` in the build settings of your target.
- **In a SwiftPM package manifest**
Enable the `InferSendableFromCaptures` upcoming feature:
```swift
.target(
name: "MyTarget",
swiftSettings: [
.enableUpcomingFeature("InferSendableFromCaptures")
]
)
```
This language feature is not enabled by default, because it can potentially [affect source compatibility](https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/sourcecompatibility#Inferring-Sendable-for-methods-and-key-path-literals).
### Non-Sendable Configuration of Record Types
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when a record type specifies which columns it fetches from the database, with the ``TableRecord/databaseSelection-7iphs`` static property:
```swift
extension Player: FetchableRecord, PersistableRecord {
// ❌ Static property 'databaseSelection' is not concurrency-safe
// because non-'Sendable' type '[any SQLSelectable]'
// may have shared mutable state
static let databaseSelection: [any SQLSelectable] = [
Column("id"), Column("name"), Column("score")
]
}
```
**To fix this error**, replace the stored property with a computed property:
```swift
extension Player: FetchableRecord, PersistableRecord {
static var databaseSelection: [any SQLSelectable] {
[Column("id"), Column("name"), Column("score")]
}
}
```
### Non-Sendable Record Types
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when the application reads, writes, or observes a non-[`Sendable`](https://developer.apple.com/documentation/swift/sendable) type.
@@ -128,97 +192,6 @@ You do not need to perform this refactoring right away: you can compile your app
Yes. Classes that can not be modified, made of constant `let` properties, are Sendable. Those immutable classes will not make it easy to modify the database, though.
#### FAQ: Why this Sendable requirement?
**GRDB needs new features in the Swift language and the SDKs in order to deal with non-Sendable types.**
[SE-0430: `sending` parameter and result values](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0430-transferring-parameters-and-results.md) looks like the language feature we need, but:
- `DispatchQueue.async` does not accept a `sending` closure. GRDB needs this in order to accept non-Sendable records to be sent to the database, as below:
```swift
let nonSendableRecord: Player
try await writer.write { db in
try nonSendableRecord.insert(db)
}
```
Please [file a feedback](http://feedbackassistant.apple.com) for requesting this DispatchQueue improvement. The more the merrier. I personally filed FB15270949.
- Database access methods taint the values they fetch. In the code below, the rules of [SE-0414: Region based Isolation](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0414-region-based-isolation.md) have the compiler refuse that the fetched player is sent back to the caller:
```swift
let player = try await writer.read { db in
try Player.fetchOne(db, id: 42)
}
```
Strictly speaking, the compiler diagnostic is correct: one could copy the non-Sendable `db` argument into the fetched `Player` instance, making it unsuitable for later use. In practice, nobody does that. Copying `db` is a programmer error, and GRDB promptly raises a fatal error whenever a `db` copy would be improperly used. But there is no way to tell the compiler about this practice.
For all those reasons, GRDB has to require values that are asynchronously written and read from the database to be `Sendable`.
### Shorthand Closure Notation
In the Swift 5 language mode, the compiler emits a warning when a database access is written with the shorthand closure notation:
```swift
// Standard closure:
let count = try await writer.read { db in
try Player.fetchCount(db)
}
// Shorthand notation:
// ⚠️ Converting non-sendable function value to '@Sendable (Database)
// throws -> Int' may introduce data races.
let count = try await writer.read(Player.fetchCount)
```
**You can remove this warning** by enabling [SE-0418: Inferring `Sendable` for methods and key path literals](https://github.com/swiftlang/swift-evolution/blob/main/proposals/0418-inferring-sendable-for-methods.md), as below:
- **Using Xcode**
Set `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` to `YES` in the build settings of your target.
- **In a SwiftPM package manifest**
Enable the `InferSendableFromCaptures` upcoming feature:
```swift
.target(
name: "MyTarget",
swiftSettings: [
.enableUpcomingFeature("InferSendableFromCaptures")
]
)
```
This language feature is not enabled by default, because it can potentially [affect source compatibility](https://www.swift.org/migration/documentation/swift-6-concurrency-migration-guide/sourcecompatibility#Inferring-Sendable-for-methods-and-key-path-literals).
### Non-Sendable Configuration of Record Types
In the Swift 6 language mode, and in the Swift 5 language mode with strict concurrency checkings, the compiler emits an error or a warning when a record type specifies which columns it fetches from the database, with the ``TableRecord/databaseSelection-7iphs`` static property:
```swift
extension Player: FetchableRecord, MutablePersistableRecord {
// ❌ Static property 'databaseSelection' is not concurrency-safe
// because non-'Sendable' type '[any SQLSelectable]'
// may have shared mutable state
static let databaseSelection: [any SQLSelectable] = [
Column("id"), Column("name"), Column("score")
]
}
```
**To fix this error**, replace the stored property with a computed property:
```swift
extension Player: FetchableRecord, MutablePersistableRecord {
static var databaseSelection: [any SQLSelectable] {
[Column("id"), Column("name"), Column("score")]
}
}
```
### Choosing between Synchronous and Asynchronous Database Accesses
GRDB connections provide two versions of `read` and `write`, one that is synchronous, and one that is asynchronous. It might not be clear how to choose one or the other.
+3
View File
@@ -1,4 +1,5 @@
// Fixits for changes introduced by GRDB 7.0.0
// swiftlint:disable all
extension Configuration {
@available(*, unavailable, message: "The default transaction kind is now automatically managed.")
@@ -15,3 +16,5 @@ extension DatabasePool {
@available(*, unavailable, message: "concurrentRead has been removed. Use `asyncConcurrentRead` instead.")
public func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T> { preconditionFailure() }
}
// swiftlint:enable all
+97 -61
View File
@@ -40,6 +40,10 @@ import Foundation
/// - ``completedMigrations(_:)``
/// - ``hasBeenSuperseded(_:)``
/// - ``hasCompletedMigrations(_:)``
///
/// ### Detecting Schema Changes
///
/// - ``hasSchemaChanges(_:)``
public struct DatabaseMigrator: Sendable {
/// Controls how a migration handle foreign keys constraints.
public enum ForeignKeyChecks: Sendable {
@@ -102,6 +106,8 @@ public struct DatabaseMigrator: Sendable {
/// migrator.eraseDatabaseOnSchemaChange = true
/// #endif
/// ```
///
/// See also ``hasSchemaChanges(_:)``.
public var eraseDatabaseOnSchemaChange = false
private var defersForeignKeyChecks = true
private var _migrations: [Migration] = []
@@ -279,6 +285,96 @@ public struct DatabaseMigrator: Sendable {
}
}
// MARK: - Detecting Schema Changes
/// Returns a boolean value indicating whether the migrator detects a
/// change in the definition of migrations.
///
/// The result is true if one of those conditions is met:
///
/// - A migration has been removed, or renamed.
/// - There exists any difference in the `sqlite_master` table, which
/// contains the SQL used to create database tables, indexes,
/// triggers, and views.
///
/// This method supports the ``eraseDatabaseOnSchemaChange`` option.
/// When `eraseDatabaseOnSchemaChange` does not exactly fit your
/// needs, you can implement it manually as below:
///
/// ```swift
/// #if DEBUG
/// // Speed up development by nuking the database when migrations change
/// if dbQueue.read(migrator.hasSchemaChanges) {
/// try dbQueue.erase()
/// // Perform other needed logic
/// }
/// #endif
/// try migrator.migrate(dbQueue)
/// ```
///
public func hasSchemaChanges(_ db: Database) throws -> Bool {
let appliedIdentifiers = try appliedIdentifiers(db)
let knownIdentifiers = Set(_migrations.map { $0.identifier })
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
// Database contains an unknown migration
return true
}
if let lastAppliedIdentifier = _migrations
.map(\.identifier)
.last(where: { appliedIdentifiers.contains($0) })
{
// Some migrations were already applied.
//
// Let's migrate a temporary database up to the same
// level, and compare the database schemas. If they
// differ, we'll return true
let tmpSchema = try {
// Make sure the temporary database is configured
// just as the migrated database
var tmpConfig = db.configuration
tmpConfig.readonly = false // We need write access
tmpConfig.targetQueue = nil // Avoid deadlocks
tmpConfig.writeTargetQueue = 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.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(.main)
}
}()
// Only compare user objects
func isUserObject(_ object: SchemaObject) -> Bool {
!Database.isSQLiteInternalTable(object.name) && !Database.isGRDBInternalTable(object.name)
}
let tmpUserSchema = tmpSchema.filter(isUserObject)
let userSchema = try db.schema(.main).filter(isUserObject)
if userSchema != tmpUserSchema {
return true
}
}
return false
}
// MARK: - Querying Migrations
/// The list of registered migration identifiers, in the same order as they
@@ -409,69 +505,9 @@ public struct DatabaseMigrator: Sendable {
if eraseDatabaseOnSchemaChange {
var needsErase = false
try db.inTransaction(.deferred) {
let appliedIdentifiers = try appliedIdentifiers(db)
let knownIdentifiers = Set(_migrations.map { $0.identifier })
if !appliedIdentifiers.isSubset(of: knownIdentifiers) {
// Database contains an unknown migration
needsErase = true
return .commit
}
if let lastAppliedIdentifier = _migrations
.map(\.identifier)
.last(where: { appliedIdentifiers.contains($0) })
{
// Some migrations were already applied.
//
// 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 = try {
// Make sure the temporary database is configured
// just as the migrated database
var tmpConfig = db.configuration
tmpConfig.targetQueue = nil // Avoid deadlocks
tmpConfig.writeTargetQueue = 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.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(.main)
}
}()
// Only compare user objects
func isUserObject(_ object: SchemaObject) -> Bool {
!Database.isSQLiteInternalTable(object.name) && !Database.isGRDBInternalTable(object.name)
}
let tmpUserSchema = tmpSchema.filter(isUserObject)
let userSchema = try db.schema(.main).filter(isUserObject)
if userSchema != tmpUserSchema {
needsErase = true
return .commit
}
}
needsErase = try hasSchemaChanges(db)
return .commit
}
if needsErase {
try db.erase()
}
@@ -458,11 +458,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
}
return filterWhenConnected(keys: { [databaseTableName] db in
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
let column = primaryKey.columns[0]
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
let strategy = recordType.databaseDataEncodingStrategy(for: column)
let expressions = try datas.map { try strategy.encode($0).sqlExpression }
return expressions
@@ -475,11 +471,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
}
return filterWhenConnected(keys: { [databaseTableName] db in
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
let column = primaryKey.columns[0]
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
let strategy = recordType.databaseDateEncodingStrategy(for: column)
let expressions = dates.map { strategy.encode($0).sqlExpression }
return expressions
@@ -492,11 +484,7 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
}
return filterWhenConnected(keys: { [databaseTableName] db in
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
let column = primaryKey.columns[0]
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
let strategy = recordType.databaseUUIDEncodingStrategy(for: column)
let expressions = uuids.map { strategy.encode($0).sqlExpression }
return expressions
@@ -524,12 +512,8 @@ extension TableRequest where Self: FilteredRequest, Self: TypedRequest {
// Don't bother removing NULLs. We'd lose CPU cycles, and this does not
// change the SQLite results anyway.
let expressions = try keys(db)
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
return SQLCollection.array(expressions).contains(Column(primaryKey.columns[0]).sqlExpression)
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
return SQLCollection.array(expressions).contains(Column(column).sqlExpression)
}
}
@@ -2168,6 +2168,7 @@ extension SQLExpressible where Self == Column {
/// - ``average(_:filter:)``
/// - ``capitalized``
/// - ``cast(_:as:)-1dmu3``
/// - ``coalesce(_:)``
/// - ``count(_:)``
/// - ``count(distinct:)``
/// - ``dateTime(_:_:)``
@@ -71,6 +71,32 @@ public func cast(_ expression: some SQLSpecificExpressible, as storageClass: Dat
.cast(expression.sqlExpression, as: storageClass)
}
/// The `COALESCE` SQL function.
///
/// For example:
///
/// ```swift
/// // COALESCE(value1, value2, ...)
/// coalesce([Column("value1"), Column("value2"), ...])
/// ```
///
/// Unlike the SQL function, `coalesce` accepts any number of arguments.
/// When `values` is empty, the result is `NULL`. When `values` contains a
/// single value, the result is this value. `COALESCE` is used from
/// two values upwards.
public func coalesce(_ values: some Collection<any SQLSpecificExpressible>) -> SQLExpression {
// SQLite COALESCE wants at least two arguments.
// There is no reason to apply the same limitation.
guard let value = values.first else {
return .null
}
if values.count > 1 {
return .function("COALESCE", values.map { $0.sqlExpression })
} else {
return value.sqlExpression
}
}
/// The `COUNT` SQL function.
///
/// For example:
+2 -5
View File
@@ -744,13 +744,10 @@ extension TableRecord {
/// any error that prevented the `RecordError` from being constructed.
public static func recordNotFound(_ db: Database, key: some DatabaseValueConvertible) -> any Error {
do {
let primaryKey = try db.primaryKey(databaseTableName)
GRDBPrecondition(
primaryKey.columns.count == 1,
"Requesting by key requires a single-column primary key in the table \(databaseTableName)")
let column = try db.filteringPrimaryKeyColumn(databaseTableName)
return RecordError.recordNotFound(
databaseTableName: databaseTableName,
key: [primaryKey.columns[0]: key.databaseValue])
key: [column: key.databaseValue])
} catch {
return error
}
+3
View File
@@ -1,3 +1,6 @@
#if !canImport(Darwin)
@preconcurrency import Dispatch
#endif
import Foundation
// MARK: - Public
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (C) 2015-2024 Gwendal Roué
Copyright (C) 2015-2025 Gwendal Roué
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+17 -45
View File
@@ -10,12 +10,12 @@
</p>
<p align="center">
<a href="https://developer.apple.com/swift/"><img alt="Swift 5.7" src="https://img.shields.io/badge/swift-5.7-orange.svg?style=flat"></a>
<a href="https://developer.apple.com/swift/"><img alt="Swift 6" src="https://img.shields.io/badge/swift-6-orange.svg?style=flat"></a>
<a href="https://github.com/groue/GRDB.swift/blob/master/LICENSE"><img alt="License" src="https://img.shields.io/github/license/groue/GRDB.swift.svg?maxAge=2592000"></a>
<a href="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml"><img alt="CI Status" src="https://github.com/groue/GRDB.swift/actions/workflows/CI.yml/badge.svg?branch=master"></a>
</p>
**Latest release**: September 29, 2024 • [version 7.0.0-beta](https://github.com/groue/GRDB.swift/tree/v7.0.0-beta) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Latest release**: October 13, 2024 • [version 7.0.0-beta.6](https://github.com/groue/GRDB.swift/tree/v7.0.0-beta.6) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 6 to GRDB 7](Documentation/GRDB7MigrationGuide.md)
**Requirements**: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 7.0+ &bull; SQLite 3.20.0+ &bull; Swift 6+ / Xcode 16+
@@ -295,7 +295,7 @@ Documentation
#### Records and the Query Interface
- [Records](#records): Fetching and persistence methods for your custom structs and class hierarchies
- [Query Interface](#the-query-interface): A swift way to generate SQL &bull; [create tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) &bull; [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md)
- [Query Interface](#the-query-interface): A swift way to generate SQL &bull; [create tables, indexes, etc](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databaseschema) &bull; [requests](#requests) • [associations between record types](Documentation/AssociationsBasics.md)
#### Application Tools
@@ -441,7 +441,7 @@ Advanced topics:
- [Prepared Statements]
- [Custom SQL Functions and Aggregates](#custom-sql-functions-and-aggregates)
- [Database Schema Introspection](#database-schema-introspection)
- [Database Schema Introspection](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databaseschemaintrospection)
- [Row Adapters](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter)
- [Raw SQLite Pointers](#raw-sqlite-pointers)
@@ -841,6 +841,13 @@ row[...] as Int?
> if let int = row[...] as Int? { ... } // GOOD
> ```
> **Warning**: avoid nil-coalescing row values, and prefer the `coalesce` method instead:
>
> ```swift
> let name: String? = row["nickname"] ?? row["name"] // BAD - doesn't work
> let name: String? = row.coalesce(["nickname", "name"]) // GOOD
> ```
Generally speaking, you can extract the type you need, provided it can be converted from the underlying SQLite value:
- **Successful conversions include:**
@@ -1589,41 +1596,6 @@ try Int.fetchOne(db, request) // Int?
```
## Database Schema Introspection
GRDB comes with a set of schema introspection methods:
```swift
try dbQueue.read { db in
// Bool, true if the table exists
try db.tableExists("player")
// [ColumnInfo], the columns in the table
try db.columns(in: "player")
// PrimaryKeyInfo
try db.primaryKey("player")
// [ForeignKeyInfo], the foreign keys defined on the table
try db.foreignKeys(on: "player")
// [IndexInfo], the indexes defined on the table
try db.indexes(on: "player")
// Bool, true if column(s) is a unique key (primary key or unique index)
try db.table("player", hasUniqueKey: ["email"])
}
// Bool, true if argument is the name of an internal SQLite table
Database.isSQLiteInternalTable(...)
// Bool, true if argument is the name of an internal GRDB table
Database.isGRDBInternalTable(...)
```
For more information, see [`tableExists(_:)`](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/database/tableexists(_:)) and related methods.
## Raw SQLite Pointers
**If not all SQLite APIs are exposed in GRDB, you can still use the [SQLite C Interface](https://www.sqlite.org/c3ref/intro.html) and call [SQLite C functions](https://www.sqlite.org/c3ref/funclist.html).**
@@ -1671,14 +1643,14 @@ try dbQueue.write { db in
}
```
Of course, you need to open a [database connection], and [create database tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema) first.
Of course, you need to open a [database connection], and [create database tables](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databaseschema) first.
To define a record type, define a type and extend it with protocols that come with focused sets of features.
For example:
```
struct Player: {
```swift
struct Player {
var id: Int64
var name: String
var score: Int
@@ -3278,7 +3250,7 @@ So don't miss the [SQL API](#sqlite-api).
> **Note**: the generated SQL may change between GRDB releases, without notice: don't have your application rely on any specific SQL output.
- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseschema)
- [The Database Schema](https://swiftpackageindex.com/groue/grdb.swift/v7.0.0-beta.6/documentation/grdb/databaseschema)
- [Requests](#requests)
- [Expressions](#expressions)
- [SQL Operators](#sql-operators)
@@ -3936,9 +3908,9 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli
GRDB comes with a Swift version of many SQLite [built-in functions](https://sqlite.org/lang_corefunc.html), listed below. But not all: see [Embedding SQL in Query Interface Requests] for a way to add support for missing SQL functions.
- `ABS`, `AVG`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`, `TOTAL`:
- `ABS`, `AVG`, `COALESCE`, `COUNT`, `DATETIME`, `JULIANDAY`, `LENGTH`, `MAX`, `MIN`, `SUM`, `TOTAL`:
Those are based on the `abs`, `average`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min`, `sum` and `total` Swift functions:
Those are based on the `abs`, `average`, `coalesce`, `count`, `dateTime`, `julianDay`, `length`, `max`, `min`, `sum`, and `total` Swift functions:
```swift
// SELECT MIN(score), MAX(score) FROM player
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>7.0.0-beta</string>
<string>7.0.0-beta.6</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -655,9 +655,11 @@ class DatabaseMigratorTests : GRDBTestCase {
var migrator = DatabaseMigrator()
migrator.eraseDatabaseOnSchemaChange = true
migrator.registerMigration("1", migrate: { _ in })
try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges))
try migrator.migrate(dbQueue)
migrator.registerMigration("2", migrate: { _ in })
try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges))
try migrator.migrate(dbQueue)
}
@@ -669,12 +671,50 @@ class DatabaseMigratorTests : GRDBTestCase {
var migrator = DatabaseMigrator()
migrator.eraseDatabaseOnSchemaChange = true
migrator.registerMigration("1", migrate: { _ in })
try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges))
try migrator.migrate(dbQueue)
migrator.registerMigration("2", migrate: { _ in })
try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges))
try migrator.migrate(dbQueue)
}
func testHasSchemaChangesWorksWithReadonlyConfig() throws {
// 1st version of the migrator
var migrator1 = DatabaseMigrator()
migrator1.registerMigration("1") { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
}
// 2nd version of the migrator
var migrator2 = DatabaseMigrator()
migrator2.registerMigration("1") { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
t.column("score", .integer) // <- schema change, because reasons (development)
}
}
let dbName = ProcessInfo.processInfo.globallyUniqueString
let dbQueue = try makeDatabaseQueue(filename: dbName)
try XCTAssertFalse(dbQueue.read(migrator1.hasSchemaChanges))
try migrator1.migrate(dbQueue)
try XCTAssertFalse(dbQueue.read(migrator1.hasSchemaChanges))
try dbQueue.close()
// check that the migrator doesn't fail for a readonly connection
dbConfiguration.readonly = true
let readonlyQueue = try makeDatabaseQueue(filename: dbName)
try XCTAssertFalse(readonlyQueue.read(migrator1.hasSchemaChanges))
try XCTAssertTrue(readonlyQueue.read(migrator2.hasSchemaChanges))
}
func testEraseDatabaseOnSchemaChange() throws {
// 1st version of the migrator
var migrator1 = DatabaseMigrator()
@@ -714,10 +754,58 @@ class DatabaseMigratorTests : GRDBTestCase {
// ... unless database gets erased
migrator2.eraseDatabaseOnSchemaChange = true
try XCTAssertTrue(dbQueue.read(migrator2.hasSchemaChanges))
try migrator2.migrate(dbQueue)
try XCTAssertFalse(dbQueue.read(migrator2.hasSchemaChanges))
try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1", "2"])
}
func testManualEraseDatabaseOnSchemaChange() throws {
// 1st version of the migrator
var migrator1 = DatabaseMigrator()
migrator1.registerMigration("1") { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
}
}
// 2nd version of the migrator
var migrator2 = DatabaseMigrator()
migrator2.registerMigration("1") { db in
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
t.column("score", .integer) // <- schema change, because reasons (development)
}
}
migrator2.registerMigration("2") { db in
try db.execute(sql: "INSERT INTO player (id, name, score) VALUES (NULL, 'Arthur', 1000)")
}
// Apply 1st migrator
let dbQueue = try makeDatabaseQueue()
try migrator1.migrate(dbQueue)
// Test than 2nd migrator can't run...
do {
try migrator2.migrate(dbQueue)
XCTFail("Expected DatabaseError")
} catch let error as DatabaseError {
XCTAssertEqual(error.resultCode, .SQLITE_ERROR)
XCTAssertEqual(error.message, "table player has no column named score")
}
try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1"])
// ... unless database gets erased
if try dbQueue.read(migrator2.hasSchemaChanges) {
try dbQueue.erase()
}
try migrator2.migrate(dbQueue)
try XCTAssertFalse(dbQueue.read(migrator2.hasSchemaChanges))
try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1", "2"])
}
func testEraseDatabaseOnSchemaChangeWithConfiguration() throws {
// 1st version of the migrator
var migrator1 = DatabaseMigrator()
@@ -763,7 +851,9 @@ class DatabaseMigratorTests : GRDBTestCase {
// ... unless database gets erased
migrator2.eraseDatabaseOnSchemaChange = true
try XCTAssertTrue(dbQueue.read(migrator2.hasSchemaChanges))
try migrator2.migrate(dbQueue)
try XCTAssertFalse(dbQueue.read(migrator2.hasSchemaChanges))
try XCTAssertEqual(dbQueue.read(migrator2.appliedMigrations), ["1", "2"])
}
@@ -792,6 +882,7 @@ class DatabaseMigratorTests : GRDBTestCase {
CREATE TABLE t2(id INTEGER PRIMARY KEY);
""")
}
try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges))
try migrator.migrate(dbQueue)
try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, sql: "SELECT id FROM t1") }, 1)
try XCTAssertTrue(dbQueue.read { try $0.tableExists("t2") })
@@ -818,6 +909,7 @@ class DatabaseMigratorTests : GRDBTestCase {
}
// Then 2nd migration does not erase database
try XCTAssertFalse(dbQueue.read(migrator.hasSchemaChanges))
try migrator.migrate(dbQueue)
try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, sql: "SELECT id FROM t") }, 1)
}
@@ -845,7 +937,9 @@ class DatabaseMigratorTests : GRDBTestCase {
INSERT INTO t1(id) VALUES (2)
""")
}
try XCTAssertTrue(dbQueue.read(migrator2.hasSchemaChanges))
try migrator2.migrate(dbQueue)
try XCTAssertFalse(dbQueue.read(migrator2.hasSchemaChanges))
try XCTAssertEqual(dbQueue.read { try Int.fetchOne($0, sql: "SELECT id FROM t1") }, 2)
}
@@ -388,12 +388,35 @@ class DatabaseQueueSchemaCacheTests : GRDBTestCase {
try main.inDatabase { db in
try db.execute(literal: "ATTACH DATABASE \(attached.path) AS attached")
let tableExists = try db.tableExists("t")
let viewExists = try db.viewExists("v")
let triggerExists = try db.triggerExists("tr")
XCTAssertTrue(tableExists)
XCTAssertTrue(viewExists)
XCTAssertTrue(triggerExists)
try XCTAssertTrue(db.tableExists("t"))
try XCTAssertTrue(db.viewExists("v"))
try XCTAssertTrue(db.triggerExists("tr"))
try XCTAssertFalse(db.tableExists("t", in: "main"))
try XCTAssertFalse(db.viewExists("v", in: "main"))
try XCTAssertFalse(db.triggerExists("tr", in: "main"))
try XCTAssertTrue(db.tableExists("t", in: "attached"))
try XCTAssertTrue(db.viewExists("v", in: "attached"))
try XCTAssertTrue(db.triggerExists("tr", in: "attached"))
}
}
func testExistsWithUnspecifiedSchemaFindsTempSchema() throws {
try makeDatabaseQueue().inDatabase { db in
try db.execute(sql: """
CREATE TEMPORARY TABLE t (id INTEGER);
CREATE TEMPORARY VIEW v AS SELECT * FROM t;
""")
try XCTAssertTrue(db.tableExists("t"))
try XCTAssertTrue(db.viewExists("v"))
try XCTAssertTrue(db.tableExists("t", in: "temp"))
try XCTAssertTrue(db.viewExists("v", in: "temp"))
try XCTAssertFalse(db.tableExists("t", in: "main"))
try XCTAssertFalse(db.viewExists("v", in: "main"))
}
}
}
@@ -1535,6 +1535,22 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
"SELECT CAST(\"name\" AS BLOB) FROM \"readers\"")
}
func testCoalesceExpression() throws {
let dbQueue = try makeDatabaseQueue()
XCTAssertEqual(
sql(dbQueue, tableRequest.select(coalesce([]))),
"SELECT NULL FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(coalesce([Col.name]))),
"SELECT \"name\" FROM \"readers\"")
XCTAssertEqual(
sql(dbQueue, tableRequest.select(coalesce([Col.name, Col.age]))),
"SELECT COALESCE(\"name\", \"age\") FROM \"readers\"")
}
func testLengthExpression() throws {
let dbQueue = try makeDatabaseQueue()
@@ -287,4 +287,29 @@ class RowCopiedFromStatementTests: RowTestCase {
XCTAssertEqual(row.debugDescription, "[null:NULL int:1 double:1.1 string:\"foo\" data:Data(6 bytes)]")
}
}
func testCoalesce() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let values = try Row
.fetchAll(db, sql: """
SELECT 'Artie' AS nickname, 'Arthur' AS name
UNION ALL SELECT NULL, 'Jacob'
UNION ALL SELECT NULL, NULL
""")
.map { row in
[
row.coalesce(Array<String>()) as String?,
row.coalesce(["nickname"]) as String?,
row.coalesce(["nickname", "name"]) as String?,
row.coalesce([Column("nickname"), Column("name")]) as String?,
]
}
XCTAssertEqual(values, [
[nil, "Artie", "Artie", "Artie"],
[nil, nil, "Jacob", "Jacob"],
[nil, nil, nil, nil],
])
}
}
}
@@ -232,4 +232,25 @@ class RowFromDictionaryLiteralTests : RowTestCase {
XCTAssertEqual(row.description, "[a:0 b:1 c:2]")
XCTAssertEqual(row.debugDescription, "[a:0 b:1 c:2]")
}
func testCoalesce() throws {
let rows: [Row] = [
["nickname": "Artie", "name": "Arthur"],
["nickname": nil, "name": "Jacob"],
["nickname": nil, "name": nil],
]
let values = rows.map { row in
[
row.coalesce(Array<String>()) as String?,
row.coalesce(["nickname"]) as String?,
row.coalesce(["nickname", "name"]) as String?,
row.coalesce([Column("nickname"), Column("name")]) as String?,
]
}
XCTAssertEqual(values, [
[nil, "Artie", "Artie", "Artie"],
[nil, nil, "Jacob", "Jacob"],
[nil, nil, nil, nil],
])
}
}
@@ -224,4 +224,25 @@ class RowFromDictionaryTests : RowTestCase {
let debugVariants: Set<String> = ["[a:0 b:\"foo\"]", "[b:\"foo\" a:0]"]
XCTAssert(debugVariants.contains(row.debugDescription))
}
func testCoalesce() throws {
let rows = [
Row(["nickname": "Artie", "name": "Arthur"]),
Row(["nickname": nil, "name": "Jacob"]),
Row(["nickname": nil, "name": nil]),
]
let values = rows.map { row in
[
row.coalesce(Array<String>()) as String?,
row.coalesce(["nickname"]) as String?,
row.coalesce(["nickname", "name"]) as String?,
row.coalesce([Column("nickname"), Column("name")]) as String?,
]
}
XCTAssertEqual(values, [
[nil, "Artie", "Artie", "Artie"],
[nil, nil, "Jacob", "Jacob"],
[nil, nil, nil, nil],
])
}
}
@@ -380,4 +380,29 @@ class RowFromStatementTests : RowTestCase {
XCTAssertTrue(rowFetched)
}
}
func testCoalesce() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let values = try Array(Row
.fetchCursor(db, sql: """
SELECT 'Artie' AS nickname, 'Arthur' AS name
UNION ALL SELECT NULL, 'Jacob'
UNION ALL SELECT NULL, NULL
""")
.map { row in
[
row.coalesce(Array<String>()) as String?,
row.coalesce(["nickname"]) as String?,
row.coalesce(["nickname", "name"]) as String?,
row.coalesce([Column("nickname"), Column("name")]) as String?,
]
})
XCTAssertEqual(values, [
[nil, "Artie", "Artie", "Artie"],
[nil, nil, "Jacob", "Jacob"],
[nil, nil, nil, nil],
])
}
}
}