Merge branch 'development'

This commit is contained in:
Gwendal Roué committed 2023-04-10 15:06:33 +02:00
commit 18e06a78a3
78 files changed
+1228 -1142

No files matched your search

+8 -1
View File
@@ -7,7 +7,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
#### 6.x Releases
- `6.10.x` Releases - [6.10.0](#6100) - [6.10.1](#6101)
- `6.10.x` Releases - [6.10.0](#6100) - [6.10.1](#6101) - [6.10.2](#6102)
- `6.9.x` Releases - [6.9.0](#690) - [6.9.1](#691) - [6.9.2](#692)
- `6.8.x` Releases - [6.8.0](#680)
- `6.7.x` Releases - [6.7.0](#670)
@@ -108,6 +108,13 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
---
## 6.10.2
Released April 10, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.1...v6.10.2)
- **Documentation Update**: The [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) guide has moved to DocC.
- **Documentation Update**: The [Demo Applications](Documentation/DemoApps/) demonstrate how their `AppDatabase` "database manager" can provide a base database configuration.
## 6.10.1
Released April 1, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.10.0...v6.10.1)
+3 -3
View File
@@ -2000,7 +2000,7 @@ Each association included in the request can feed a property of the decoded reco
- [Decoding a Joined Request with a Decodable Record]
- [Decoding a Joined Request with FetchableRecord]
- [Debugging Request Decoding]
- [Good Practices for Designing Record Types] - in this general guide about records, check out the "Compose Records" chapter.
- [Recommended Practices for Designing Record Types] - in this general guide about records, check out the "Associations" chapter.
## The Structure of a Joined Request
@@ -2860,7 +2860,7 @@ extension DerivableRequest<Book> {
}
```
See [Good Practices for Designing Record Types] for more information.
See [Recommended Practices for Designing Record Types] for more information.
## Known Issues
@@ -2999,7 +2999,7 @@ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[Row Adapters]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/rowadapter
[query interface requests]: ../README.md#requests
[TableRecord]: ../README.md#tablerecord-protocol
[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md
[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices
[regular aggregating methods]: ../README.md#fetching-aggregated-values
[Record class]: ../README.md#record-class
[EncodableRecord]: ../README.md#persistablerecord-protocol
@@ -61,6 +61,13 @@
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "SQL_TRACE"
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,12 +1,29 @@
import Foundation
import GRDB
import os.log
/// AppDatabase lets the application access the database.
/// A database of players.
///
/// It applies the pratices recommended at
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
/// You create an `AppDatabase` with a connection to an SQLite database
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
///
/// Create those connections with a configuration returned from
/// `AppDatabase/makeConfiguration(_:)`.
///
/// For example:
///
/// ```swift
/// // Create an in-memory AppDatabase
/// let config = AppDatabase.makeConfiguration()
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
struct AppDatabase {
/// Creates an `AppDatabase`, and make sure the database schema is ready.
/// Creates an `AppDatabase`, and makes sure the database schema
/// is ready.
///
/// - important: Create the `DatabaseWriter` with a configuration
/// returned by ``makeConfiguration(_:)``.
init(_ dbWriter: any DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
@@ -19,18 +36,67 @@ struct AppDatabase {
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
}
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
// An opportunity to add required custom SQL functions or
// collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
// Log SQL statements 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 {
config.prepareDatabase { db in
db.trace {
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
}
}
}
#if DEBUG
// Protect sensitive information by enabling verbose debugging in
// DEBUG builds only.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
config.publicStatementArguments = true
#endif
return config
}
}
// MARK: - Database Migrations
extension AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
#if DEBUG
// Speed up development by nuking the database when migrations change
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
@@ -52,6 +118,7 @@ struct AppDatabase {
}
// MARK: - Database Access: Writes
// The write methods execute invariant-preserving database transactions.
extension AppDatabase {
/// A validation error that prevents some players from being saved into
@@ -127,8 +194,8 @@ extension AppDatabase {
}
}
}
static let uiTestPlayers = [
private static let uiTestPlayers = [
Player(id: nil, name: "Arthur", score: 5),
Player(id: nil, name: "Barbara", score: 6),
Player(id: nil, name: "Craig", score: 8),
@@ -137,7 +204,7 @@ extension AppDatabase {
Player(id: nil, name: "Frederik", score: 2),
Player(id: nil, name: "Gilbert", score: 7),
Player(id: nil, name: "Henriette", score: 3)]
func createPlayersForUITests() throws {
try dbWriter.write { db in
try AppDatabase.uiTestPlayers.forEach { player in
@@ -7,26 +7,31 @@ extension AppDatabase {
private static func makeShared() -> AppDatabase {
do {
// Pick a folder for storing the SQLite database, as well as
// the various temporary files created during normal database
// operations (https://sqlite.org/tempfiles.html).
let fileManager = FileManager()
let folderURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
//
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
let appSupportURL = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
// Support for tests: delete the database if requested
if CommandLine.arguments.contains("-reset") {
try? fileManager.removeItem(at: folderURL)
try? fileManager.removeItem(at: directoryURL)
}
// Create the database folder if needed
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
// Connect to a database on disk
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Open or create the database
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
NSLog("Database stored at \(databaseURL.path)")
let dbPool = try DatabasePool(
path: databaseURL.path,
// Use default AppDatabase configuration
configuration: AppDatabase.makeConfiguration())
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
@@ -59,7 +64,7 @@ extension AppDatabase {
static func empty() -> AppDatabase {
// Connect to an in-memory database
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbQueue = try! DatabaseQueue()
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
return try! AppDatabase(dbQueue)
}
@@ -69,8 +69,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// Define some player requests used by the application.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
extension DerivableRequest<Player> {
/// A request of players ordered by name.
///
@@ -5,7 +5,7 @@ import GRDB
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_inserts() async throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
@@ -35,7 +35,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_updates() async throws {
// Given a players database that contains a player
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = try await dbQueue.write { db in
try Player(id: nil, name: "Arthur", score: 100).inserted(db)
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
func test_deletePlayers() async throws {
// Given a players database that contains four players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
let playerIds: [Int64] = try await dbQueue.write { db in
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
func test_deleteAllPlayers() async throws {
// Given a players database that contains players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
try await dbQueue.write { db in
_ = try Player(id: nil, name: "Arthur", score: 100).inserted(db)
@@ -102,7 +102,7 @@ class AppDatabaseTests: XCTestCase {
func test_refreshPlayers_populates_an_empty_database() async throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
@@ -115,7 +115,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
@@ -127,7 +127,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -5,7 +5,7 @@ import GRDB
class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
@@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
func testInsert() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -14,7 +14,7 @@ The topics covered in this demo are:
- How to setup a database in an iOS app.
- How to define a simple [Codable Record](../../../README.md#codable-records).
- How to track database changes and animate a SwiftUI List with an async sequence built from [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
- How to feed SwiftUI previews with a transient database.
**Files of interest:**
@@ -61,6 +61,13 @@
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "SQL_TRACE"
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,13 +1,29 @@
import Combine
import Foundation
import GRDB
import os.log
/// AppDatabase lets the application access the database.
/// A database of players.
///
/// It applies the pratices recommended at
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
/// You create an `AppDatabase` with a connection to an SQLite database
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
///
/// Create those connections with a configuration returned from
/// `AppDatabase/makeConfiguration(_:)`.
///
/// For example:
///
/// ```swift
/// // Create an in-memory AppDatabase
/// let config = AppDatabase.makeConfiguration()
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
struct AppDatabase {
/// Creates an `AppDatabase`, and make sure the database schema is ready.
/// Creates an `AppDatabase`, and makes sure the database schema
/// is ready.
///
/// - important: Create the `DatabaseWriter` with a configuration
/// returned by ``makeConfiguration(_:)``.
init(_ dbWriter: any DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
@@ -20,18 +36,67 @@ struct AppDatabase {
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
}
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
// An opportunity to add required custom SQL functions or
// collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
// Log SQL statements 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 {
config.prepareDatabase { db in
db.trace {
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
}
}
}
#if DEBUG
// Protect sensitive information by enabling verbose debugging in
// DEBUG builds only.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
config.publicStatementArguments = true
#endif
return config
}
}
// MARK: - Database Migrations
extension AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
#if DEBUG
// Speed up development by nuking the database when migrations change
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
@@ -53,6 +118,7 @@ struct AppDatabase {
}
// MARK: - Database Access: Writes
// The write methods execute invariant-preserving database transactions.
extension AppDatabase {
/// A validation error that prevents some players from being saved into
@@ -128,8 +194,8 @@ extension AppDatabase {
}
}
}
static let uiTestPlayers = [
private static let uiTestPlayers = [
Player(id: nil, name: "Arthur", score: 5),
Player(id: nil, name: "Barbara", score: 6),
Player(id: nil, name: "Craig", score: 8),
@@ -138,7 +204,7 @@ extension AppDatabase {
Player(id: nil, name: "Frederik", score: 2),
Player(id: nil, name: "Gilbert", score: 7),
Player(id: nil, name: "Henriette", score: 3)]
func createPlayersForUITests() throws {
try dbWriter.write { db in
try AppDatabase.uiTestPlayers.forEach { player in
@@ -7,26 +7,31 @@ extension AppDatabase {
private static func makeShared() -> AppDatabase {
do {
// Pick a folder for storing the SQLite database, as well as
// the various temporary files created during normal database
// operations (https://sqlite.org/tempfiles.html).
let fileManager = FileManager()
let folderURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
//
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
let appSupportURL = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
// Support for tests: delete the database if requested
if CommandLine.arguments.contains("-reset") {
try? fileManager.removeItem(at: folderURL)
try? fileManager.removeItem(at: directoryURL)
}
// Create the database folder if needed
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
// Connect to a database on disk
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Open or create the database
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
NSLog("Database stored at \(databaseURL.path)")
let dbPool = try DatabasePool(
path: databaseURL.path,
// Use default AppDatabase configuration
configuration: AppDatabase.makeConfiguration())
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
@@ -59,7 +64,7 @@ extension AppDatabase {
static func empty() -> AppDatabase {
// Connect to an in-memory database
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbQueue = try! DatabaseQueue()
let dbQueue = try! DatabaseQueue(configuration: AppDatabase.makeConfiguration())
return try! AppDatabase(dbQueue)
}
@@ -69,8 +69,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// Define some player requests used by the application.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
extension DerivableRequest<Player> {
/// A request of players ordered by name.
///
@@ -5,7 +5,7 @@ import GRDB
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_inserts() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_updates() throws {
// Given a players database that contains a player
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
func test_deletePlayers() throws {
// Given a players database that contains four players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
func test_deleteAllPlayers() throws {
// Given a players database that contains players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
func test_refreshPlayers_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -5,7 +5,7 @@ import GRDB
class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byName_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
@@ -24,7 +24,7 @@ class PlayerRequestTests: XCTestCase {
func test_PlayerRequest_byScore_fetches_well_ordered_players() throws {
// Given a players database that contains two players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 1000)
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
func testInsert() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -14,7 +14,7 @@ The topics covered in this demo are:
- How to setup a database in an iOS app.
- How to define a simple [Codable Record](../../../README.md#codable-records).
- How to track database changes and animate a SwiftUI List with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation) Combine publishers.
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
- How to feed SwiftUI previews with a transient database.
**Files of interest:**
@@ -61,6 +61,13 @@
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<EnvironmentVariables>
<EnvironmentVariable
key = "SQL_TRACE"
value = "1"
isEnabled = "NO">
</EnvironmentVariable>
</EnvironmentVariables>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -1,11 +1,28 @@
import GRDB
import os.log
/// AppDatabase lets the application access the database.
/// `AppDatabase` lets the application access the database.
///
/// It applies the pratices recommended at
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
final class AppDatabase {
/// Creates an `AppDatabase`, and make sure the database schema is ready.
/// You create an `AppDatabase` with a connection to an SQLite database
/// (see <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>).
///
/// Create those connections with a configuration returned from
/// `AppDatabase/makeConfiguration(_:)`.
///
/// For example:
///
/// ```swift
/// // Create an in-memory AppDatabase
/// let config = AppDatabase.makeConfiguration()
/// let dbQueue = try DatabaseQueue(configuration: config)
/// let appDatabase = try AppDatabase(dbQueue)
/// ```
struct AppDatabase {
/// Creates an `AppDatabase`, and makes sure the database schema
/// is ready.
///
/// - important: Create the `DatabaseWriter` with a configuration
/// returned by ``makeConfiguration(_:)``.
init(_ dbWriter: any DatabaseWriter) throws {
self.dbWriter = dbWriter
try migrator.migrate(dbWriter)
@@ -18,18 +35,67 @@ final class AppDatabase {
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
private let dbWriter: any DatabaseWriter
}
// MARK: - Database Configuration
extension AppDatabase {
private static let sqlLogger = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "SQL")
/// Returns a database configuration suited for `PlayerRepository`.
///
/// SQL statements are logged if the `SQL_TRACE` environment variable
/// is set.
///
/// - parameter base: A base configuration.
public static func makeConfiguration(_ base: Configuration = Configuration()) -> Configuration {
var config = base
// An opportunity to add required custom SQL functions or
// collations, if needed:
// config.prepareDatabase { db in
// db.add(function: ...)
// }
// Log SQL statements 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 {
config.prepareDatabase { db in
db.trace {
// It's ok to log statements publicly. Sensitive
// information (statement arguments) are not logged
// unless config.publicStatementArguments is set
// (see below).
os_log("%{public}@", log: sqlLogger, type: .debug, String(describing: $0))
}
}
}
#if DEBUG
// Protect sensitive information by enabling verbose debugging in
// DEBUG builds only.
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/configuration/publicstatementarguments>
config.publicStatementArguments = true
#endif
return config
}
}
// MARK: - Database Migrations
extension AppDatabase {
/// The DatabaseMigrator that defines the database schema.
///
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
private var migrator: DatabaseMigrator {
var migrator = DatabaseMigrator()
#if DEBUG
#if DEBUG
// Speed up development by nuking the database when migrations change
// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations>
migrator.eraseDatabaseOnSchemaChange = true
#endif
#endif
migrator.registerMigration("createPlayer") { db in
// Create a table
@@ -51,6 +117,7 @@ final class AppDatabase {
}
// MARK: - Database Access: Writes
// The write methods execute invariant-preserving database transactions.
extension AppDatabase {
/// Saves (inserts or updates) a player. When the method returns, the
@@ -7,19 +7,24 @@ extension AppDatabase {
private static func makeShared() -> AppDatabase {
do {
// Create a folder for storing the SQLite database, as well as
// the various temporary files created during normal database
// operations (https://sqlite.org/tempfiles.html).
let fileManager = FileManager()
let folderURL = try fileManager
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("database", isDirectory: true)
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
// Apply recommendations from
// <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections>
//
// Create the "Application Support/Database" directory if needed
let fileManager = FileManager.default
let appSupportURL = try fileManager.url(
for: .applicationSupportDirectory, in: .userDomainMask,
appropriateFor: nil, create: true)
let directoryURL = appSupportURL.appendingPathComponent("Database", isDirectory: true)
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
// Connect to a database on disk
// See https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseconnections
let dbURL = folderURL.appendingPathComponent("db.sqlite")
let dbPool = try DatabasePool(path: dbURL.path)
// Open or create the database
let databaseURL = directoryURL.appendingPathComponent("db.sqlite")
NSLog("Database stored at \(databaseURL.path)")
let dbPool = try DatabasePool(
path: databaseURL.path,
// Use default AppDatabase configuration
configuration: AppDatabase.makeConfiguration())
// Create the AppDatabase
let appDatabase = try AppDatabase(dbPool)
@@ -68,8 +68,7 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
/// Define some player requests used by the application.
///
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
extension DerivableRequest<Player> {
/// A request of players ordered by name.
///
@@ -5,7 +5,7 @@ import GRDB
class AppDatabaseTests: XCTestCase {
func test_database_schema() throws {
// Given an empty database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
// When we instantiate an AppDatabase
_ = try AppDatabase(dbQueue)
@@ -21,7 +21,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_inserts() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we save a new player
@@ -34,7 +34,7 @@ class AppDatabaseTests: XCTestCase {
func test_savePlayer_updates() throws {
// Given a players database that contains a player
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -55,7 +55,7 @@ class AppDatabaseTests: XCTestCase {
func test_deletePlayers() throws {
// Given a players database that contains four players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -83,7 +83,7 @@ class AppDatabaseTests: XCTestCase {
func test_deleteAllPlayers() throws {
// Given a players database that contains players
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player1 = Player(id: nil, name: "Arthur", score: 100)
var player2 = Player(id: nil, name: "Barbara", score: 200)
@@ -105,7 +105,7 @@ class AppDatabaseTests: XCTestCase {
func test_refreshPlayers_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we refresh players
@@ -117,7 +117,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
// When we create random players
@@ -129,7 +129,7 @@ class AppDatabaseTests: XCTestCase {
func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws {
// Given a players database that contains one player
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
let appDatabase = try AppDatabase(dbQueue)
var player = Player(id: nil, name: "Arthur", score: 100)
try dbQueue.write { db in
@@ -8,7 +8,7 @@ class PlayerTests: XCTestCase {
func testInsert() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player
@@ -23,7 +23,7 @@ class PlayerTests: XCTestCase {
func testRoundtrip() throws {
// Given an empty players database
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
// When we insert a player and fetch the player with the same id
@@ -42,7 +42,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScore() throws {
// Given a players database that contains players with distinct scores
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -64,7 +64,7 @@ class PlayerTests: XCTestCase {
func testOrderedByScoreSortsIdenticalScoresByName() throws {
// Given a players database that contains players with common scores
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
@@ -86,7 +86,7 @@ class PlayerTests: XCTestCase {
func testOrderedByName() throws {
// Given a players database that contains players with distinct names
let dbQueue = try DatabaseQueue()
let dbQueue = try DatabaseQueue(configuration: AppDatabase.makeConfiguration())
_ = try AppDatabase(dbQueue)
var player1 = Player(id: 1, name: "Arthur", score: 100)
var player2 = Player(id: 2, name: "Barbara", score: 200)
+1 -1
View File
@@ -14,7 +14,7 @@ The topics covered in this demo are:
- How to setup a database in an iOS app.
- How to define a simple [Codable Record](../../../README.md#codable-records).
- How to track database changes and animate a table view with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
**Files of interest:**
@@ -1,836 +1,4 @@
Good Practices for Designing Record Types
=========================================
This guide aims at helping you leverage the best of GRDB [records] and [associations].
Since GRDB sits right between low-level libraries like SQLite itself or [FMDB], and high-level ORM like [Core Data] or [Realm], you may face questions when designing the model layer of your application.
To support this guide, we'll design a simple library application that lets the user crawl through books and their authors.
- [Trust SQLite More Than Yourself]
- [Persistable Record Types are Responsible for Their Tables]
- [Record Types Hide Intimate Database Details]
- [Singleton Records]
- [Define Record Requests]
- [Compose Records]
- [How to Design Database Managers]
- [Observe the Database and Refetch when Needed]
## Trust SQLite More Than Yourself
It is important to put things in the right order. An SQLite database stored on one of your user's device is more important than the Swift code that accesses it. When a user installs a new version of your application, all the code may change, but the database remains the same.
This is why we recommend defining a **robust database schema** even before playing with record types.
SQLite is a battle-tested database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk.
This is important because we developers write bugs, and some of them will ship in the wild, affecting the users of our applications. But SQLite will prevent many of those bugs from corrupting our precious users' data.
For example, if we were to define a [migration] that sets up our library database, made of books and their authors, we could write:
```swift
var migrator = DatabaseMigrator()
migrator.registerMigration("createLibrary") { db in
try db.create(table: "author") { t in // (1)
t.autoIncrementedPrimaryKey("id") // (2)
t.column("name", .text).notNull() // (3)
t.column("country", .text) // (4)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull() // (5)
t.column("authorId", .integer) // (6)
.notNull() // (7)
.indexed() // (8)
.references("author", onDelete: .cascade) // (9)
}
}
try migrator.migrate(dbQueue)
```
1. Our database table names follow the [recommended convention]: they 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.
5. A book must have a title.
6. The `book.authorId` column is used to link a book to the author it belongs to.
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
8. The `book.authorId` column is indexed in order to ease the selection of an author's books.
9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
Thanks to this database schema, you can be confident that no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc.
> :bulb: **Tip**: Don't look at your local SQLite database as you look at the JSON you load from a remote server. You can't control the JSON, its format and content: your application must defend itself against wacky servers. But you can control the database. Put the database on your side, make it trustable. Learn about relational databases, and how they can help you guarantee the quality of your application data. Put as much energy as you can in the proper definition of your database schema.
>
> :bulb: **Tip**: Plan early for future versions of your application, and use [migrations].
>
> :bulb: **Tip**: In the definition of your migrations, define tables and their columns with **strings**:
>
> ```swift
> migrator.registerMigration("createLibrary") { db in
> // RECOMMENDED
> try db.create(table: "author") { t in
> t.autoIncrementedPrimaryKey("id")
> ...
> }
>
> // NOT RECOMMENDED
> try db.create(table: Author.databaseTableName) { t in
> t.autoIncrementedPrimaryKey(Author.Columns.id.name)
> ...
> }
> }
> ```
>
> By using strings, you make sure that you will not have to change the Swift code of your migrations in the future. Even if author columns eventually change. Even if the Author type eventually gets replaced with another type. Even when your startup eventually pivots and starts selling pet food. A good migration that never changes is easy to test once and for good. A good migration that never changes will run smoothly on all devices in the wild, even if a user upgrades straight from version 1.0 to version 5.0 of your application.
>
> So make sure that migrations don't use application types and values: migrations should talk to the database, only to the database, and use the database language: **strings**.
## Persistable Record Types are Responsible for Their Tables
Define one record type per database table, and make it adopt a [PersistableRecord] protocol.
In this sample code, we'll use Codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
```swift
struct Author: Codable, Identifiable {
var id: Int64?
var name: String
var country: String?
}
struct Book: Codable, Identifiable {
var id: Int64?
var authorId: Int64
var title: String
}
```
We add database powers to our types with [record protocols]. Since our records use auto-incremented ids, we provide an implementation of the `didInsert` method:
```swift
// Add Database access
extension Author: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
extension Book: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
```
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`.
> :bulb: **Tip**: When a column of a database table can't be NULL, store it in a non-optional property of your record type. On the other side, when the database may contain NULL, define an optional property.
>
> :bulb: **Tip**: When a database table uses an auto-incremented identifier, make the `id` property optional (so that you can instantiate a record before it gets inserted and gains an id), and implement the `didInsert(_:)` method:
>
> ```swift
> try dbQueue.write { db in
> var author = Author(id: nil, name: "Hermann Melville", country: "United States")
> try author.insert(db)
> print(author.id!) // Guaranteed non-nil id
> }
> ```
>
> :bulb: **Tip**: When the database table has a single-column primary key, have your record type adopt the standard [Identifiable] protocol. This allows GRDB to define type-safe id-related methods:
>
> ```swift
> let authorID: Int64 = ...
> let author: Author? = try dbQueue.read { db in
> try Author.fetchOne(db, id: authorID)
> }
> ```
Now that `Author` and `Book` can read and write in their own database tables, they are responsible for it. Make sure each record type deals with one database table, and only one database table!
## Record Types Hide Intimate Database Details
The application uses `Book` and `Author` as regular structs, using their properties. Each of those properties matches a column in the database (`Book.title`, `Author.id`), and is defined with a Swift type that is natively supported by SQLite (`String`, `Int`, etc.)
Sometimes, it happens that raw database column names and types are not a very good fit for the application.
Let's look at three examples:
1. Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. For easy debugging of the database contents, a book kind is represented as a string ("novel", "essay", etc.):
```swift
try db.create(table: "book") { t in
...
t.column("kind", .text).notNull()
}
```
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We want an enum instead:
```swift
struct Book: Codable {
enum Kind: String, Codable {
case novel, poems, essay, play
}
var id: Int64?
var authorId: Int64
var title: String
var kind: Kind
}
```
In order to make it possible to use `Book.Kind` in book requests (see [Define Record Requests] below), we add this conformance:
```swift
extension Book.Kind: DatabaseValueConvertible { }
```
> :bulb: Records can pick the best suited [Value] type for their column properties (Bool, Int, String, Date, etc.) Thanks to its enum property, the `Book` record prevents unknown book kinds from entering the database.
2. GPS coordinates are usually stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
When this happens, keep column properties private, and provide sensible accessors instead:
```swift
struct Place: Codable {
var id: Int64?
var name: String
private var latitude: CLLocationDegrees
private var longitude: CLLocationDegrees
var coordinate: CLLocationCoordinate2D {
get {
CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
}
```
> :bulb: Private properties make it possible to hide raw columns from the rest of the application.
3. The record below exposes a `price: Decimal` property ($12.00), backed by an integer column that stores a quantity of cents (1200). An integer column is preferred because it allows SQLite to compute exact sums of prices.
```swift
struct Product: Codable {
var id: Int64?
var name: String
private var priceCents: Int
var price: Decimal {
get { Decimal(priceCents) / 100 }
set { priceCents = NSDecimalNumber(decimal: newValue * 100).intValue }
}
}
```
> :bulb: Private properties allow records to choose both their best database representation, and at the same time, their best Swift interface.
**Generally speaking**, record types are the dedicated place, in your code, where you can transform raw database values into well-suited types that the rest of the application will enjoy. When needed, you can even [validate values](../README.md#persistence-callbacks) before they enter the database.
## Singleton Records
**Singleton Records** are records that store configuration values, user preferences, and generally some global application state. They are backed by a database table that contains a single row.
The recommended setup for such records is described in the [Single-Row Tables](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/singlerowtables) guide. Go check it, and come back when you're done!
## Define Record Requests
Now that we have record types that are able to read and write in the database, we'd like to put them to good use.
> :bulb: **Tip**: Define an enumeration of columns that you will use in order to filter, sort, etc.
When your record type is a [Codable Record], derive columns from the [CodingKeys] enum:
```swift
// For a codable record
extension Author {
// Define database columns from CodingKeys
enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let country = Column(CodingKeys.country)
}
}
```
Otherwise, declare a plain `String` enum that conforms to the `ColumnExpression` protocol:
```swift
// For a non-codable record
extension Author {
// Define database columns as an enum
enum Columns: String, ColumnExpression {
case id, name, country
}
}
```
Those columns let you define requests:
```swift
try dbQueue.read { db in
// Order authors by name, in a localized case-insensitive fashion
let sortedAuthors: [Author] = try Author.all()
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
.fetchAll(db)
// French authors
let frenchAuthors: [Author] = try Author.all()
.filter(Author.Columns.country == "France")
.fetchAll(db)
}
```
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
When you find yourself build similar requests over and over in your application, you may want to define a reusable and composable request vocabulary. This will avoid repetition in your app, ease refactoring, and enable [testability](DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift).
To do so, extend the `DerivableRequest` protocol. It generally lets you filter, sort, leverage associations (we'll talk about associations in the [Compose Records] chapter below), etc:
```swift
// Author requests
extension DerivableRequest<Author> {
/// Order authors by name, in a localized case-insensitive fashion
func orderByName() -> Self {
let name = Author.Columns.name
return order(name.collating(.localizedCaseInsensitiveCompare))
}
/// Filters authors from a country
func filter(country: String) -> Self {
filter(Author.Columns.country == country)
}
/// Filters authors with at least one book
func havingBooks() -> Self {
having(Author.books.isEmpty == false)
}
}
```
Those methods encapsulate intimate database details, and allow you to compose database requests in a fluent and legible style:
```swift
try dbQueue.read { db in
let sortedAuthors: [Author] = try Author.all()
.orderByName()
.fetchAll(db)
let frenchAuthors: [Author] = try Author.all()
.filter(country: "France")
.fetchAll(db)
let sortedSpanishAuthorsHavingBooks: [Author] = try Author.all()
.filter(country: "Spain")
.havingBooks()
.orderByName()
.fetchAll(db)
}
```
Because they are defined in an extension of the `DerivableRequest` protocol, our customized methods can decorate both requests and associations. See how the implementation of `filter(authorCountry:)` for books, below, uses the `filter(country:)` for authors:
```swift
// Book requests
extension DerivableRequest<Book> {
/// Filters books by kind
func filter(kind: Book.Kind) -> Self {
filter(Book.Columns.kind == kind)
}
/// Filters books from a country
func filter(authorCountry: String) -> Self {
// Books do not have any country column. But their author has one.
// A book is from a country if it can be joined to an author from this country:
joining(required: Book.author.filter(country: authorCountry))
}
}
try dbQueue.read { db in
let italianNovels: [Book] = try Book.all()
.filter(kind: .novel)
.filter(authorCountry: "Italy")
.fetchAll(db)
}
```
Extensions to the `DerivableRequest` protocol can not change the type of requests. This has to be expressed in an extension to `QueryInterfaceRequest`. For example:
```swift
// Author requests
extension QueryInterfaceRequest<Author> {
// Selects author ids
func selectId() -> QueryInterfaceRequest<Int64> {
selectPrimaryKey(as: Int64.self)
}
}
// IDs of French authors
let ids: [Int64] = try Author.all().filter(country: "France").selectId().fetchAll(db)
```
## Compose Records
We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations:
```swift
extension Author {
static let books = hasMany(Book.self)
}
extension Book {
static let author = belongsTo(Author.self)
}
```
Thanks to this setup, you can fetch associated records, or compute aggregated values from associated records. For example:
```swift
// Fetch all authors and their number of books
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookCount: Int
}
let authorInfos: [AuthorInfo] = try dbQueue.read { db in
let request = Author.annotated(with: Author.books.count)
return try AuthorInfo.fetchAll(db, request)
}
// Fetch all Colombian books and their authors:
struct Authorship: Decodable, FetchableRecord {
var book: Book
var author: Author
}
let authorships: [Authorship] = try dbQueue.read { db in
let request = Book.including(required: Book.author.filter(country: "Colombia"))
return try Authorship.fetchAll(db, request)
}
```
As in the sample code above, requests which feed from several associated records will often have you define extra record types, such as `AuthorInfo` and `Authorship`. Those extra record types are designed to be able to decode database requests. The names and types of their properties follow the conventions defined by [associations]. Make them conform to the Decodable and FetchableRecord protocols so that they can decode database rows in a breeze.
Unlike the primitive persistable record types `Author` and `Book`, those records can not write in the database. They are simple data types, passive views on the database content. Remember, only [Persistable Record Types are Responsible for Their Tables].
> **Note**: The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they?
>
> That is because other ORMs perform lazy loading:
>
> ```ruby
> # Ruby's Active Record
> author = Author.find(123) # fetch author
> book_count = author.books.count # lazily counts books on demand
> ```
>
> GRDB does not perform lazy loading. Lazy loading either requires records to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer.
>
> This is why GRDB has removed lazy loading from the list of desirable features. Instead, it provides the tooling needed to fetch data, even complex ones, in a single and safe stroke. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information.
Granted with primitive and derived record types, your application will load the data it needs, at the moment it needs it, as below:
1. Prepare the application screen that lists all authors:
```swift
let authors: [Author] = try dbQueue.read { db in
try Author.all().orderByName().fetchAll(db)
}
```
2. Prepare the application screen that displays an author and her books:
```swift
struct AuthorInfo: Codable, FetchableRecord {
var author: Author
var books: [Book]
}
let authorId = 123
let authorInfo: AuthorInfo? = try dbQueue.read { db in
let request = Author
.filter(id: authorId)
.including(all: Author.books)
return try AuthorInfo.fetchOne(db, request)
}
```
3. Prepare the application screen that displays a book information:
```swift
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var author: Author
}
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
let request = Book
.filter(id: bookId)
.including(required: Book.author)
return try BookInfo.fetchOne(db, request)
}
```
> :bulb: **Tip**: Identify the various **graph of objects** needed by the various parts of your application. Design them independently, by composing primitive record types linked by associations. Fetch the data your application needs, at the moment it needs it, no more, no less.
A last extension on your record types will further help navigation from records to associated ones:
```swift
extension Author {
/// The request for the author's books
var books: QueryInterfaceRequest<Book> {
request(for: Author.books)
}
}
extension Book {
/// The request for the author of the book
var author: QueryInterfaceRequest<Author> {
request(for: Book.author)
}
}
```
Those properties provide an alternative way to feed our application:
1. Prepare the application screen that displays an author and her books:
```swift
struct AuthorInfo {
var author: Author
var books: [Book]
}
let authorId = 123
let authorInfo: AuthorInfo? = try dbQueue.read { db in
guard let author = try Author.fetchOne(db, id: authorId) else {
return nil
}
let books = try author.books.fetchAll(db)
return AuthorInfo(
author: author,
books: books)
}
```
2. Prepare the application screen that displays a book information:
```swift
struct BookInfo {
var book: Book
var author: Author
}
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
guard let book = try Book.fetchOne(db, id: bookId) else {
return nil
}
guard let author = try book.author.fetchOne(db) else {
return nil
}
return BookInfo(book: book, author: author)
}
```
## How to Design Database Managers
Many developers want to hide GRDB database queues and pools inside "database managers":
```swift
// LibraryManager grants access to the library database.
class LibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
}
```
> :bulb: **Tip**: Don't let your database managers create their own databases. Instead, give them a database created by, say, the ApplicationDelegate. This will allow you to efficiently test the database manager with an in-memory database, for example.
Design your database managers with the [GRDB concurrency rules] in mind.
Practically, let's start with a naive example, and gradually improve it:
```swift
// A naive manager that we will improve
class NaiveLibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
func author(id: Int64) -> Author? {
do {
return try dbQueue.read { db in
try Author.fetchOne(db, id: id)
}
} catch {
return nil
}
}
func book(id: Int64) -> Book? {
do {
return try dbQueue.read { db in
try Book.fetchOne(db, id: id)
}
} catch {
return nil
}
}
func books(writtenBy author: Author) -> [Book] {
do {
return try dbQueue.read { db in
try author.books.fetchAll(db)
}
} catch {
return []
}
}
}
```
**This manager can be improved in two ways.**
- [Embrace Errors]
- [Thread-Safety is also an Application Concern]
### Embrace Errors
Have database managers throw database errors instead of catching them.
Consider Apple's [CNContactStore](https://developer.apple.com/documentation/contacts/cncontactstore), for example. Does it hide errors when you fetch or save address book contacts? No it does not. Keychain, Media assets, File system, Core Data? No they do not hide errors either. Follow the practices of Apple engineers: do not hide errors :muscle:
Exposing errors will help you building your application:
- You will be able to inspect errors during development, and fix bugs. `do { ... } catch { print(error) }` will save you hours of clueless questioning.
- You will be able to opt in for advanced OS features like [data protection].
> :bulb: **Tip**: Don't hide database errors. Let the application handle them, because only application can decide how to handle them.
This gives the improved manager below. And it has less code, which means less bugs :bowtie:
```swift
// An improved manager that does not hide errors
class ImprovedLibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
func author(id: Int64) throws -> Author? {
try dbQueue.read { db in
try Author.fetchOne(db, id: id)
}
}
func book(id: Int64) throws -> Book? {
try dbQueue.read { db in
try Book.fetchOne(db, id: id)
}
}
func books(writtenBy author: Author) throws -> [Book] {
try dbQueue.read { db in
try author.books.fetchAll(db)
}
}
}
```
### Thread-Safety is also an Application Concern
Now, let's make our database manager **thread-safe**.
This one is more subtle. In order to understand what is wrong in our naive manager, one has to consider how it is used by the application.
For example, in the screen that displays an author and her books, we would write:
```swift
let authorId = 123
if let author = libraryManager.author(id: authorId) {
let books = libraryManager.books(writtenBy: author)
// Use author and books
}
```
This code is not thread-safe, because other application threads may have modified the database between the two database accesses. You may end up with an author without any book, and this sure does not make a pretty application screen.
Such bugs are uneasy to reproduce. Sometimes your application will refresh the library content from the network, and delete an author right at the wrong time. The more users your application has, the more users will see weird screens. And of course, you'll be bitten right on the day of the demo in front of the boss.
Fortunately, GRDB has all the tools you need to prevent such nasty data races:
> :bulb: **Tip**: Make sure you fetch all the data your application needs at a given moment of time, in a **single database read**.
This gives a much safer manager:
```swift
// A manager that actually manages
class LibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
}
// Feeds the list of authors
extension LibraryManager {
struct AuthorListItem: Decodable, FetchableRecord {
let author: Author
let bookCount: Int
}
func authorList() throws -> [AuthorListItem] {
try dbQueue.read { db in
let request = Author
.annotated(with: Author.books.count)
.orderByName()
return try AuthorListItem.fetchAll(db, request)
}
}
}
// Feeds a book screen
extension LibraryManager {
struct BookInfo {
var book: Book
var author: Author
}
func bookInfo(bookId: Int64) throws -> BookInfo? {
try dbQueue.read { db in
guard let book = try Book.fetchOne(db, id: bookId) else {
return nil
}
guard let author = try book.author.fetchOne(db) else {
return nil
}
return BookInfo(book: book, author: author)
}
}
}
// Feeds an author screen
extension LibraryManager {
struct AuthorInfo {
var author: Author
var books: [Book]
}
func authorInfo(authorId: Int64) throws -> AuthorInfo? {
try dbQueue.read { db in
guard let author = try Author.fetchOne(db, id: authorId) else {
return nil
}
let books = try author.books.fetchAll(db)
return AuthorInfo(author: author, books: books)
}
}
}
```
The `AuthorListItem`, `BookInfo`, `AuthorInfo` types returned by the manager are designed to feed your views.
When a new screen is added to your application, and you want to make sure it displays **consistent data** free from any data race, make sure you update the manager if needed. The rule is very simple: consumed data must come from a **single** database access method (`dbQueue.read`, `write`, etc.), or [ValueObservation].
In other words: since GRDB is an unmanaged ORM, some amount of management must be imported into your application in order to make it fully thread-safe.
> **Note**: Wrapping several fetches in a single `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
>
> ```ruby
> # Ruby's Active Record
> book = Book.find(123) # fetch book
> author = book.author # fetch author
> # use book and author
> ```
>
> The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests.
>
> This isolation can be achieved with record management, as in [Core Data] or [Realm], that target long-running multi-threaded applications. On the other side, most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others.
>
> GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. But unlike web-oriented ORMs, GRDB can't provide implicit isolation: the application must decide when it wants to safely read information in the database, and this decision is made explicit, in your application code, with database access methods such as `dbQueue.read`.
>
> See the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale.
## Observe the Database and Refetch when Needed
We have seen above that the primitive Author and Book record types are [responsible](#persistable-record-types-are-responsible-for-their-tables) for their own database tables. Later we built [requests](#define-record-requests) and [composed](#compose-records) records into more complex ones such as BookInfo or AuthorInfo. We have shown how [database managers](#how-to-design-database-managers) should expose database content to the rest of the application.
Database content which has been fetched into memory eventually becomes obsoleted, as the application modifies the database content.
It is up to the application to decide how long it should keep fetched information in memory. Very often though, the application will want to keep memory information synchronized with the database content.
This synchronization is not automatic with GRDB: records do not "auto-update". That is because applications do not always want this feature, and because it is difficult to write correct multi-threaded applications when values can change in unexpected ways.
Instead, have a look at [Database Observation]:
> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes.
>
> :bulb: **Tip**: [Combine Support] allows automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way.
>
> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way.
>
> :bulb: **Tip**: [TransactionObserver] provides low-level database observation, for your most advanced needs.
>
> :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones.
[records]: ../README.md#records
[associations]: AssociationsBasics.md
[FMDB]: https://github.com/ccgus/fmdb
[Core Data]: https://developer.apple.com/documentation/coredata
[Realm]: https://realm.io
[Active Record]: http://guides.rubyonrails.org/active_record_basics.html
[Django]: https://docs.djangoproject.com/en/2.0/topics/db/
[record protocols]: ../README.md#record-protocols-overview
[Separation of Concerns]: https://en.wikipedia.org/wiki/Separation_of_concerns
[Single Source of Truth]: https://en.wikipedia.org/wiki/Single_source_of_truth
[Divide and Conquer]: https://en.wikipedia.org/wiki/Divide_and_rule
[Why Adopt GRDB?]: WhyAdoptGRDB.md
[isolation]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
[migrations]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
[migration]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations
[Foreign Key Actions]: https://sqlite.org/foreignkeys.html#fk_actions
[Concurrency Guide]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
[GRDB concurrency rules]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/concurrency
[PersistableRecord]: ../README.md#persistablerecord-protocol
[Database Observation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[ValueObservation]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation
[RxGRDB]: https://github.com/RxSwiftCommunity/RxGRDB
[TransactionObserver]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/transactionobserver
[Trust SQLite More Than Yourself]: #trust-sqlite-more-than-yourself
[Persistable Record Types are Responsible for Their Tables]: #persistable-record-types-are-responsible-for-their-tables
[Record Types Hide Intimate Database Details]: #record-types-hide-intimate-database-details
[Singleton Records]: #singleton-records
[Define Record Requests]: #define-record-requests
[Compose Records]: #compose-records
[How to Design Database Managers]: #how-to-design-database-managers
[Observe the Database and Refetch when Needed]: #observe-the-database-and-refetch-when-needed
[query interface]: ../README.md#the-query-interface
[observe database changes]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/databaseobservation
[data protection]: ../README.md#data-protection
[Embrace Errors]: #embrace-errors
[Thread-Safety is also an Application Concern]: #thread-safety-is-also-an-application-concern
[recommended convention]: AssociationsBasics.md#associations-and-the-database-schema
[Association Aggregates]: AssociationsBasics.md#association-aggregates
[Codable Record]: ../README.md#codable-records
[CodingKeys]: https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types
[Combine Support]: Combine.md
[Value]: ../README.md#values
[Identifiable]: https://developer.apple.com/documentation/swift/identifiable
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
+1 -1
View File
@@ -195,7 +195,7 @@ protocol DerivableRequest<RowDecoder>: AggregatingRequest, FilteredRequest,
- `SelectionRequest` provides selection methods such as `select(selection)` or `annotated(with: selection)`
- `TableRequest` provides table targeting methods such as `aliased(tableAlias)`
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) and [Associations](AssociationsBasics.md).
DerivableRequest makes it possible to build reusable code snippets that apply to both requests and associations. You'll read more about it in the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) and [Associations](AssociationsBasics.md).
### FetchRequest
+2 -2
View File
@@ -90,7 +90,7 @@ For your convenience, those record protocols can be derived from the [Decodable
Being a protocol-oriented library that welcomes immutable types, GRDB records are unlike records in other ORM libraries. Particularly, records do not auto-update, and records are not uniqued. We'll see below that the lack of those features can be replaced with **database change notifications**, with many advantages.
See [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) for some practical advice.
See [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for some practical advice.
### Allow database records to cross threads
@@ -190,7 +190,7 @@ Finally, raw FMDatabase, SQLite.swift, and Core Data are the hardest tools, and
For detailed information about GRDB concurrency, check the [Concurrency Guide].
For practical advice on designing the database access layer of your application, see the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md).
For practical advice on designing the database access layer of your application, see the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
### Never pay for using raw SQL
+1 -1
View File
@@ -1,6 +1,6 @@
Pod::Spec.new do |s|
s.name = 'GRDB.swift'
s.version = '6.10.1'
s.version = '6.10.2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
-10
View File
@@ -512,7 +512,6 @@
56419A6C24A51601004967E1 /* Support.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Support.swift; sourceTree = "<group>"; };
56419A6D24A51601004967E1 /* DatabaseRegionObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DatabaseRegionObservationPublisherTests.swift; sourceTree = "<group>"; };
56419A6E24A51601004967E1 /* ValueObservationPublisherTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueObservationPublisherTests.swift; sourceTree = "<group>"; };
5643676D272EDF2400C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = "<group>"; };
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
564CE43021AA901800652B19 /* ValueConcurrentObserver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ValueConcurrentObserver.swift; sourceTree = "<group>"; };
@@ -1113,13 +1112,6 @@
path = GRDBCombineTests;
sourceTree = "<group>";
};
564390D42414FC2C00BA61E6 /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
5653EABF20944B1300F46237 /* Association */ = {
isa = PBXGroup;
children = (
@@ -1588,8 +1580,6 @@
DC37742D19C8CC90004FCF85 /* GRDB */,
DC10500F19C904DD00D8CA30 /* Tests */,
DC3773F419C8CBB3004FCF85 /* Products */,
564390D42414FC2C00BA61E6 /* Frameworks */,
5643676D272EDF2400C718C7 /* Scripts */,
);
indentWidth = 4;
sourceTree = "<group>";
+1 -1
View File
@@ -182,7 +182,7 @@ public struct Configuration {
/// var config = Configuration()
/// config.transactionClock = .custom { db in /* return some Date */ }
/// ```
public var transactionClock: TransactionClock = .default
public var transactionClock: any TransactionClock = .default
// MARK: - Managing SQLite Connections
+1 -1
View File
@@ -572,7 +572,7 @@ public struct ScopeAdapter: RowAdapter {
///
/// - parameter scopes: A dictionary that maps scope names to
/// row adapters.
public init(_ scopes: [String: RowAdapter]) {
public init(_ scopes: [String: any RowAdapter]) {
// Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
}
+1 -1
View File
@@ -1030,7 +1030,7 @@ public struct StatementArguments: Hashable {
/// The result is nil unless all array elements conform to the
/// ``DatabaseValueConvertible`` protocol.
public init?(_ array: [Any]) {
var values = [DatabaseValueConvertible?]()
var values = [(any DatabaseValueConvertible)?]()
for value in array {
guard let dbValue = DatabaseValue(value: value) else {
return nil
@@ -136,7 +136,7 @@ private struct DatabaseValueDecodingContainer: SingleValueDecodingContainer {
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value is null.
func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
if let type = T.self as? DatabaseValueConvertible.Type {
if let type = T.self as? any DatabaseValueConvertible.Type {
// Prefer DatabaseValueConvertible decoding over Decodable.
// This allows custom database decoding, such as decoding Date from
// String, for example.
+2 -1
View File
@@ -27,12 +27,13 @@ Compared to [SQLite.swift](https://github.com/stephencelis/SQLite.swift) or [FMD
- <doc:DatabaseSchema>
- <doc:Migrations>
- <doc:SingleRowTables>
### Records and the Query Interface
- <doc:QueryInterface>
- <doc:RecordRecommendedPractices>
- <doc:RecordTimestamps>
- <doc:SingleRowTables>
### Responding to Database Changes
@@ -0,0 +1,581 @@
# Recommended Practices for Designing Record Types
Leverage the best of record types and associations.
## Overview
GRDB sits right between low-level SQLite wrappers, and high-level ORMs like [Core Data], so you may face questions when designing the model layer of your application.
This is the topic of this article. Examples will be illustrated with a simple library database made of books and their authors.
## Trust SQLite More Than Yourself
Let's put things in the right order. An SQLite database stored on a user's device is more important than the Swift code that accesses it. When a user installs a new version of an application, only the database stored on the user's device remains the same. But all the Swift code may have changed.
This is why it is recommended to define a **robust database schema** even before playing with record types.
This is important because SQLite is very robust, whereas we developers write bugs. The more responsibility we give to SQLite, the less code we have to write, and the fewer defects we will ship on our users' devices, affecting their precious data.
For example, if we were to define <doc:Migrations> that configure a database made of books and their authors, we could write:
```swift
var migrator = DatabaseMigrator()
migrator.registerMigration("createLibrary") { db in
try db.create(table: "author") { t in // (1)
t.autoIncrementedPrimaryKey("id") // (2)
t.column("name", .text).notNull() // (3)
t.column("countryCode", .text) // (4)
}
try db.create(table: "book") { t in
t.autoIncrementedPrimaryKey("id")
t.column("title", .text).notNull() // (5)
t.column("authorId", .integer) // (6)
.notNull() // (7)
.indexed() // (8)
.references("author", onDelete: .cascade) // (9)
}
}
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`.
2. Each author has a unique id.
3. An author must have a name.
4. The country of an author is not always known.
5. A book must have a title.
6. The `book.authorId` column is used to link a book to the author it belongs to.
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
8. The `book.authorId` column is indexed in order to ease the selection of an author's books.
9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions](https://sqlite.org/foreignkeys.html#fk_actions) for more information.
Thanks to this database schema, the application will always process *consistent data*, no matter how wrong the Swift code can get. Even after a hard crash, all books will have an author, a non-nil title, etc.
> Tip: **A local SQLite database is not a JSON payload loaded from a remote server.**
>
> The JSON format and content can not be controlled, and an application must defend itself against wacky servers. But a local database is under your full control. It is trustable. A relational database such as SQLite guarantee the quality of users data, as long as enough energy is put in the proper definition of the database schema.
> Tip: **Plan early for future versions of your application**: use <doc:Migrations>.
## Record Types
### Persistable Record Types are Responsible for Their Tables
**Define one record type per database table.** This record type will be responsible for writing in this table.
**Let's start from regular structs** whose properties match the columns in their database table. Those structs conform to the standard [`Identifiable`] protocol because they have an identifier (the primary key). They conform to the standard [`Codable`] protocol so that we don't have to write the methods that convert to and from raw database rows.
```swift
struct Author: Codable, Identifiable {
var id: Int64?
var name: String
var countryCode: String?
}
struct Book: Codable, Identifiable {
var id: Int64?
var authorId: Int64
var title: String
}
```
**We add database powers to our types with record protocols.**
The `author` and `book` tables have an auto-incremented id. We want inserted records to learn about their id after a successful insertion. That's why we have them conform to the ``MutablePersistableRecord`` protocol, and implement ``MutablePersistableRecord/didInsert(_:)-109jm``. Other kinds of record types would just use ``PersistableRecord``, and ignore `didInsert`.
On the reading side, we use ``FetchableRecord``, the protocol that can decode database rows.
This gives:
```swift
// Add Database access
extension Author: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
extension Book: FetchableRecord, MutablePersistableRecord {
// Update auto-incremented id upon successful insertion
mutating func didInsert(_ inserted: InsertionSuccess) {
id = inserted.rowID
}
}
```
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`:
```swift
try dbQueue.write { db in
// Insert and set author's id
var author = Author(name: "Herman Melville", countryCode: "US")
try author.insert(db)
// Insert and set book's id
var book = Book(authorId: author.id!, title: "Moby-Dick")
try book.insert(db)
}
let books = try dbQueue.read { db in
try Book.fetchAll(db)
}
```
> Tip: When a column of a database table can't be NULL, define a non-optional property in the record type. On the other side, when the database may contain NULL, define an optional property. Compare:
>
> ```swift
> try db.create(table: "author") { t in
> t.autoIncrementedPrimaryKey("id")
> t.column("name", .text).notNull() // Can't be NULL
> t.column("countryCode", .text) // Can be NULL
> }
>
> struct Author: Codable, Identifiable {
> var id: Int64?
> var name: String // Not optional
> var countryCode: String? // Optional
> }
> ```
>
> There are exceptions to this rule.
>
> For example, the `id` column is never NULL in the database. And yet, `Author` as an optional `id` property. That is because we want to create instances of `Author` before they could be inserted in the database, and be assigned an auto-incremented id. If the `id` property was not optional, the `Author` type could not profit from auto-incremented ids!
>
> Another exception to this rule is described in <doc:RecordTimestamps>, where the creation date of a record is never NULL in the database, but optional in the Swift type.
> Tip: When the database table has a single-column primary key, have the record type adopt the standard [`Identifiable`] protocol. This allows GRDB to define extra methods based on record ids:
>
> ```swift
> let authorID: Int64 = 42
> let author: Author = try dbQueue.read { db in
> try Author.find(db, id: authorID)
> }
> ```
### Record Types Hide Intimate Database Details
In the previous sample codes, the `Book` and `Author` structs have one property per database column, and their types are natively supported by SQLite (`String`, `Int`, etc.)
But it happens that raw database column names, or raw column types, are not a very good fit for the application.
When this happens, it's time to **distinguish the Swift and database representations**. Record types are the dedicated place where raw database values can be transformed into Swift types that are well-suited for the rest of the application.
Let's look at three examples.
#### First Example: Enums
Authors write books, and more specifically novels, poems, essays, or theatre plays. Let's add a `kind` column in the database. We decide that a book kind is represented as a string ("novel", "essay", etc.) in the database:
```swift
try db.create(table: "book") { t in
...
t.column("kind", .text).notNull()
}
```
In Swift, it is not a good practice to use `String` for the type of the `kind` property. We prefer an enum instead:
```swift
struct Book: Codable {
enum Kind: String, Codable {
case essay, novel, poetry, theater
}
var id: Int64?
var authorId: Int64
var title: String
var kind: Kind
}
```
Thanks to its enum property, the `Book` record prevents invalid book kinds from being stored into the database.
In order to use `Book.Kind` in database requests for books (see <doc:RecordRecommendedPractices#Record-Requests> below), we add the ``DatabaseValueConvertible`` conformance to `Book.Kind`:
```swift
extension Book.Kind: DatabaseValueConvertible { }
// Fetch all novels
let novels = try dbQueue.read { db in
try Book.filter(Column("kind") == Book.Kind.novel).fetchAll(db)
}
```
#### Second Example: GPS Coordinates
GPS coordinates can be stored in two distinct `latitude` and `longitude` columns. But the standard way to deal with such coordinate is a single `CLLocationCoordinate2D` struct.
When this happens, keep column properties private, and provide sensible accessors instead:
```swift
try db.create(table: "place") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("latitude", .double).notNull()
t.column("longitude", .double).notNull()
}
struct Place: Codable {
var id: Int64?
var name: String
private var latitude: CLLocationDegrees
private var longitude: CLLocationDegrees
var coordinate: CLLocationCoordinate2D {
get {
CLLocationCoordinate2D(
latitude: latitude,
longitude: longitude)
}
set {
latitude = newValue.latitude
longitude = newValue.longitude
}
}
}
```
Generally speaking, private properties make it possible to hide raw columns from the rest of the application. The next example shows another application of this technique.
#### Third Example: Money Amounts
Before storing money amounts in an SQLite database, take care that [floating-point numbers are never a good fit](https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency).
SQLite only supports two kinds of numbers: integers and doubles, so we'll store amounts as integers. $12.00 will be represented by 1200, a quantity of cents. This allows SQLite to compute exact sums of price, for example.
On the other side, an amount of cents is not very practical for the rest of the Swift application. The [`Decimal`] type looks like a better fit.
That's why the `Product` record type has a `price: Decimal` property, backed by a `priceCents` integer column:
```swift
try db.create(table: "product") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text).notNull()
t.column("priceCents", .integer).notNull()
}
struct Product: Codable {
var id: Int64?
var name: String
private var priceCents: Int
var price: Decimal {
get {
Decimal(priceCents) / 100
}
set {
priceCents = Self.cents(for: newValue)
}
}
private static func cents(for value: Decimal) -> Int {
Int(Double(truncating: NSDecimalNumber(decimal: value * 100)))
}
}
```
## Record Requests
Once we have record types that are able to read and write in the database, we'd like to perform database requests of such records.
### Columns
Requests that filter or sort records are defined with **columns**, defined in a dedicated enumeration. When the record type conforms to [`Codable`], columns can be derived from the `CodingKeys` enum:
```swift
// HOW TO define columns for a Codable record
extension Author {
enum Columns {
static let id = Column(CodingKeys.id)
static let name = Column(CodingKeys.name)
static let countryCode = Column(CodingKeys.countryCode)
}
}
```
For other record types, declare a plain `String` enum that conforms to the ``ColumnExpression`` protocol:
```swift
// HOW TO define columns for a non-Codable record
extension Author {
enum Columns: String, ColumnExpression {
case id, name, countryCode
}
}
```
From those columns it is possible to define requests of type ``QueryInterfaceRequest``:
```swift
try dbQueue.read { db in
// Fetch all authors, ordered by name,
// in a localized case-insensitive fashion
let sortedAuthors: [Author] = try Author.all()
.order(Author.Columns.name.collating(.localizedCaseInsensitiveCompare))
.fetchAll(db)
// Count French authors
let frenchAuthorCount: Int = try Author.all()
.filter(Author.Columns.countryCode == "FR")
.fetchCount(db)
}
```
### Turn Commonly-Used Requests into Methods
An application can define reusable request methods that extend the built-in GRDB apis. Those methods avoid code repetition, ease refactoring, and foster testability.
Define those methods in extensions of the ``DerivableRequest`` protocol, as below:
```swift
// Author requests
extension DerivableRequest<Author> {
/// Order authors by name, in a localized case-insensitive fashion
func orderByName() -> Self {
let name = Author.Columns.name
return order(name.collating(.localizedCaseInsensitiveCompare))
}
/// Filters authors from a country
func filter(countryCode: String) -> Self {
filter(Author.Columns.countryCode == countryCode)
}
}
// Book requests
extension DerivableRequest<Book> {
/// Order books by title, in a localized case-insensitive fashion
func orderByTitle() -> Self {
let title = Book.Columns.title
return order(title.collating(.localizedCaseInsensitiveCompare))
}
/// Filters books by kind
func filter(kind: Book.Kind) -> Self {
filter(Book.Columns.kind == kind)
}
}
```
Those methods define a fluent and legible api that encapsulates intimate database details:
```swift
try dbQueue.read { db in
let sortedSpanishAuthors: [Author] = try Author.all()
.filter(countryCode: "ES")
.orderByName()
.fetchAll(db)
let novelCount: Int = try Book.all()
.filter(kind: .novel)
.fetchCount(db)
}
```
Extensions to the `DerivableRequest` protocol can not change the type of requests. They remain requests of the base record. To define requests of another type, use an extension to ``QueryInterfaceRequest``, as in the example below:
```swift
extension QueryInterfaceRequest<Author> {
// Selects author ids
func selectId() -> QueryInterfaceRequest<Int64> {
selectPrimaryKey(as: Int64.self)
}
}
// The ids of Japanese authors
let ids: Set<Int64> = try Author.all()
.filter(countryCode: "JP")
.selectId()
.fetchSet(db)
```
## Associations
[Associations] help navigating from authors to their books and vice versa. Because the `book` table has an `authorId` column, we say that each book **belongs to** its author, and each author **has many** books:
```swift
extension Book {
static let author = belongsTo(Author.self)
}
extension Author {
static let books = hasMany(Book.self)
}
```
With associations, you can fetch a book's author, or an author's books:
```swift
// Fetch all novels from an author
try dbQueue.read { db in
let author: Author = ...
let novels: [Book] = try author.request(for: Author.books)
.filter(kind: .novel)
.orderByTitle()
.fetchAll(db)
}
```
Associations also make it possible to define more convenience request methods:
```swift
extension DerivableRequest<Book> {
/// Filters books from a country
func filter(authorCountryCode countryCode: String) -> Self {
// Books do not have any country column. But their author has one!
// Return books that can be joined to an author from this country:
joining(required: Book.author.filter(countryCode: countryCode))
}
}
// Fetch all Italian novels
try dbQueue.read { db in
let italianNovels: [Book] = try Book.all()
.filter(kind: .novel)
.filter(authorCountryCode: "IT")
.fetchAll(db)
}
```
With associations, you can also process graphs of authors and books, as described in the next section.
### How to Model Graphs of Objects
Since the beginning of this article, the `Book` and `Author` are independent structs that don't know each other. The only "meeting point" is the `Book.authorId` property.
Record types don't know each other on purpose: one does not need to know the author of a book when it's time to update the title of a book, for example.
When an application wants to process authors and books together, it defines dedicated types that model the desired view on the graph of related objects. For example:
```swift
// Fetch all authors along with their number of books
struct AuthorInfo: Decodable, FetchableRecord {
var author: Author
var bookCount: Int
}
let authorInfos: [AuthorInfo] = try dbQueue.read { db in
try Author
.annotated(with: Author.books.count)
.asRequest(of: AuthorInfo.self)
.fetchAll(db)
}
```
```swift
// Fetch the literary careers of German authors, sorted by name
struct LiteraryCareer: Codable, FetchableRecord {
var author: Author
var books: [Book]
}
let careers: [LiteraryCareer] = try dbQueue.read { db in
try Author
.filter(countryCode: "DE")
.orderByName()
.including(all: Author.books)
.asRequest(of: LiteraryCareer.self)
.fetchAll(db)
}
```
```swift
// Fetch all Colombian books and their authors
struct Authorship: Decodable, FetchableRecord {
var book: Book
var author: Author
}
let authorships: [Authorship] = try dbQueue.read { db in
try Book.all()
.including(required: Book.author.filter(countryCode: "CO"))
.asRequest(of: Authorship.self)
.fetchAll(db)
// Equivalent alternative
try Book.all()
.filter(authorCountryCode: "CO")
.including(required: Book.author)
.asRequest(of: Authorship.self)
.fetchAll(db)
}
```
In the above sample codes, requests that fetch values from several tables are decoded into additional record types: `AuthorInfo`, `LiteraryCareer`, and `Authorship`.
Those record type conform to both [`Decodable`] and ``FetchableRecord``, so that they can feed from database rows. They do not provide any persistence methods, though. **All database writes are performed from persistable record instances** (of type `Author` or `Book`).
For more information about associations, see the [Associations] guide.
### Lazy and Eager Loading: Comparison with Other Database Libraries
The additional record types described in the previous section may look superfluous. Some other database libraries are able to navigate in graphs of records without additional types.
For example, [Core Data] and Ruby's [Active Record] uses **lazy loading**. This means that relationships are lazily fetched on demand:
```ruby
# Lazy loading with Active Record
author = Author.first # Fetch first author
puts author.name
author.books.each do |book| # Lazily fetch books on demand
puts book.title
end
```
**GRDB does not perform lazy loading.** In a GUI application, lazy loading can not be achieved without record management (as in [Core Data]), which in turn comes with non-trivial pain points for developers regarding concurrency. Instead of lazy loading, the library provides the tooling needed to fetch data, even complex graphs, in an [isolated] fashion, so that fetched values accurately represent the database content, and all database invariants are preserved. See the <doc:Concurrency> guide for more information.
Vapor [Fluent] uses **eager loading**, which means that relationships are only fetched if explicitly requested:
```swift
// Eager loading with Fluent
let query = Author.query(on: db)
.with(\.$books) // <- Explicit request for books
.first()
// Fetch first author and its books in one stroke
if let author = query.get() {
print(author.name)
for book in author.books { print(book.title) }
}
```
One must take care of fetching relationships, though, or Fluent raises a fatal error:
```swift
// Oops, the books relation is not explicitly requested
let query = Author.query(on: db).first()
if let author = query.get() {
// fatal error: Children relation not eager loaded.
for book in author.books { print(book.title) }
}
```
**GRDB supports eager loading**. The difference with Fluent is that the relationships are modelled in a dedicated record type that provides full compile and runtime safety:
```swift
// Eager loading with GRDB
struct LiteraryCareer: Codable, FetchableRecord {
var author: Author
var books: [Book]
}
let request = Author.all()
.including(all: Author.books) // <- Explicit request for books
.asRequest(of: LiteraryCareer.self)
// Fetch first author and its books in one stroke
if let career = try request.fetchOne(db) {
print(career.author.name)
for book in career.books { print(book.title) }
}
```
[Active Record]: http://guides.rubyonrails.org/active_record_basics.html
[`Codable`]: https://developer.apple.com/documentation/swift/Codable
[Core Data]: https://developer.apple.com/documentation/coredata
[`Decimal`]: https://developer.apple.com/documentation/foundation/decimal
[`Decodable`]: https://developer.apple.com/documentation/swift/Decodable
[Django]: https://docs.djangoproject.com/en/4.2/topics/db/
[Fluent]: https://docs.vapor.codes/fluent/overview/
[`Identifiable`]: https://developer.apple.com/documentation/swift/identifiable
[isolated]: https://en.wikipedia.org/wiki/Isolation_(database_systems)
[Associations]: https://github.com/groue/GRDB.swift/blob/master/Documentation/AssociationsBasics.md
+1 -1
View File
@@ -57,7 +57,7 @@ extension DatabaseCursor {
extension DatabaseMigrator {
@available(*, unavailable, message: "The completion function now accepts one Result<Database, Error> argument")
public func asyncMigrate(
_ writer: DatabaseWriter,
_ writer: any DatabaseWriter,
completion: @escaping (Database, Error?) -> Void)
{ preconditionFailure() }
}
@@ -2,7 +2,6 @@ extension Database {
// MARK: - Database Schema
// TODO: deprecate just before GRDB 6
/// Creates a database table.
///
/// For example:
@@ -321,7 +320,6 @@ extension Database {
try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)")
}
// TODO: deprecate just before GRDB 6
/// Creates an index.
///
/// For example:
-2
View File
@@ -522,7 +522,6 @@
56419A7F24A51614004967E1 /* Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Map.swift; sourceTree = "<group>"; };
56419A8024A51614004967E1 /* Inverted.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Inverted.swift; sourceTree = "<group>"; };
56419A8124A51614004967E1 /* PublisherExpectation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PublisherExpectation.swift; sourceTree = "<group>"; };
5643676E272EDF3700C718C7 /* Scripts */ = {isa = PBXFileReference; lastKnownFileType = folder; path = Scripts; sourceTree = "<group>"; };
564448821EF56B1B00DD2861 /* DatabaseAfterNextTransactionCommitTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseAfterNextTransactionCommitTests.swift; sourceTree = "<group>"; };
5644DE7E20F8D1D1001FFDDE /* DatabaseValueConversionErrorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseValueConversionErrorTests.swift; sourceTree = "<group>"; };
564A50C61BFF4B7F00B3A3A2 /* DatabaseCollationTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCollationTests.swift; sourceTree = "<group>"; };
@@ -1584,7 +1583,6 @@
DC37742D19C8CC90004FCF85 /* GRDB */,
F3BA7FED1CFB21F8003DC1BA /* GRDBCustomSQLite */,
DC10500F19C904DD00D8CA30 /* Tests */,
5643676E272EDF3700C718C7 /* Scripts */,
DC3773F419C8CBB3004FCF85 /* Products */,
);
indentWidth = 4;
+3
View File
@@ -10,6 +10,9 @@ var swiftSettings: [SwiftSetting] = [
var cSettings: [CSetting] = []
var dependencies: [PackageDescription.Package.Dependency] = []
// For Swift 5.8+
//swiftSettings.append(.enableUpcomingFeature("ExistentialAny"))
// Don't rely on those environment variables. They are ONLY testing conveniences:
// $ SQLITE_ENABLE_PREUPDATE_HOOK=1 make test_SPM
if ProcessInfo.processInfo.environment["SQLITE_ENABLE_PREUPDATE_HOOK"] == "1" {
+5 -5
View File
@@ -11,13 +11,13 @@
---
**Latest release**: April 1, 2023 • [version 6.10.1](https://github.com/groue/GRDB.swift/tree/v6.10.1) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
**Latest release**: April 10, 2023 • [version 6.10.2](https://github.com/groue/GRDB.swift/tree/v6.10.2) • [CHANGELOG](CHANGELOG.md) • [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
**Requirements**: iOS 11.0+ / macOS 10.13+ / tvOS 11.0+ / watchOS 4.0+ &bull; SQLite 3.19.3+ &bull; Swift 5.7+ / Xcode 14+
| Swift version | GRDB version |
| -------------- | ----------------------------------------------------------- |
| **Swift 5.7+** | **v6.10.1** |
| **Swift 5.7+** | **v6.10.2** |
| Swift 5.3 | [v5.26.1](https://github.com/groue/GRDB.swift/tree/v5.26.1) |
| Swift 5.2 | [v5.12.0](https://github.com/groue/GRDB.swift/tree/v5.12.0) |
| Swift 5.1 | [v4.14.0](https://github.com/groue/GRDB.swift/tree/v4.14.0) |
@@ -359,7 +359,7 @@ Documentation
#### General Guides & Good Practices
- :bulb: [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md)
- :bulb: [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
- :bulb: [Migrating From GRDB 5 to GRDB 6](Documentation/GRDB6MigrationGuide.md)
- :bulb: [Issues tagged "best practices"](https://github.com/groue/GRDB.swift/issues?q=is%3Aissue+label%3A%22best+practices%22)
- :question: [Issues tagged "question"](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=is%3Aissue%20label%3Aquestion)
@@ -1706,7 +1706,7 @@ Extending structs with record protocols is more "swifty". Subclassing the Record
> **Note**: if you are familiar with Core Data's NSManagedObject or Realm's Object, you may experience a cultural shock: GRDB records are not uniqued, do not auto-update, and do not lazy-load. This is both a purpose, and a consequence of protocol-oriented programming. You should read [How to build an iOS application with SQLite and GRDB.swift](https://medium.com/@gwendal.roue/how-to-build-an-ios-application-with-sqlite-and-grdb-swift-d023a06c29b3) for a general introduction.
>
> :bulb: **Tip**: after you have read this chapter, check the [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) Guide.
> :bulb: **Tip**: after you have read this chapter, check the [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) Guide.
>
> :bulb: **Tip**: see the [Demo Applications] for sample apps that uses records.
@@ -2828,7 +2828,7 @@ extension Player: FetchableRecord, PersistableRecord {
}
```
See the [query interface](#the-query-interface) and [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) for further information.
See the [query interface](#the-query-interface) and [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for further information.
## Record Class
+1 -1
View File
@@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>6.10.1</string>
<string>6.10.2</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
@@ -395,7 +395,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
return writer
}
func test(writer: DatabaseWriter, iteration: Int) throws {
func test(writer: some DatabaseWriter, iteration: Int) throws {
// print(iteration)
let scoreSubject = PassthroughSubject<Int, Error>()
let publisher = scoreSubject
@@ -16,12 +16,12 @@ private struct B : TableRecord {
private struct RestrictedB : TableRecord {
static let databaseTableName = "b"
static let databaseSelection: [SQLSelectable] = [Column("name")]
static let databaseSelection: [any SQLSelectable] = [Column("name")]
}
private struct ExtendedB : TableRecord {
static let databaseTableName = "b"
static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
}
/// Test SQL generation
@@ -16,12 +16,12 @@ private struct B : TableRecord {
private struct RestrictedB : TableRecord {
static let databaseTableName = "b"
static let databaseSelection: [SQLSelectable] = [Column("name")]
static let databaseSelection: [any SQLSelectable] = [Column("name")]
}
private struct ExtendedB : TableRecord {
static let databaseTableName = "b"
static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
}
/// Test SQL generation
@@ -19,12 +19,12 @@ private struct C: TableRecord {
private struct RestrictedC : TableRecord {
static let databaseTableName = "c"
static let databaseSelection: [SQLSelectable] = [Column("name")]
static let databaseSelection: [any SQLSelectable] = [Column("name")]
}
private struct ExtendedC : TableRecord {
static let databaseTableName = "c"
static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
}
/// Test SQL generation
+4 -4
View File
@@ -20,7 +20,7 @@ class ColumnExpressionTests: GRDBTestCase {
}
// Test databaseSelection
static let databaseSelection: [SQLSelectable] = [Columns.id, Columns.name, Columns.score]
static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score]
init(row: Row) {
// Test row subscript
@@ -80,7 +80,7 @@ class ColumnExpressionTests: GRDBTestCase {
}
// Test databaseSelection
static let databaseSelection: [SQLSelectable] = [Columns.id, Columns.name, Columns.score]
static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score]
init(row: Row) {
// Test row subscript
@@ -148,7 +148,7 @@ class ColumnExpressionTests: GRDBTestCase {
}
// Test databaseSelection
static let databaseSelection: [SQLSelectable] = [Columns.id, Columns.name, Columns.score]
static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score]
static var testRequest: QueryInterfaceRequest<Player> {
// Test expression derivation
@@ -196,7 +196,7 @@ class ColumnExpressionTests: GRDBTestCase {
}
// Test databaseSelection
static let databaseSelection: [SQLSelectable] = [CodingKeys.id, CodingKeys.name, CodingKeys.score]
static let databaseSelection: [any SQLSelectable] = [CodingKeys.id, CodingKeys.name, CodingKeys.score]
static var testRequest: QueryInterfaceRequest<Player> {
// Test expression derivation
@@ -27,13 +27,13 @@ private struct UserDatabaseAggregate1 : DatabaseAggregate {
let a: Int?
init() { a = nil }
mutating func step(_ dbValues: [DatabaseValue]) throws { }
func finalize() throws -> DatabaseValueConvertible? { preconditionFailure() }
func finalize() throws -> (any DatabaseValueConvertible)? { preconditionFailure() }
}
private class UserDatabaseAggregate2 : DatabaseAggregate {
required init() { }
func step(_ dbValues: [DatabaseValue]) throws { }
func finalize() throws -> DatabaseValueConvertible? { preconditionFailure() }
func finalize() throws -> (any DatabaseValueConvertible)? { preconditionFailure() }
}
// MARK: - DatabaseValueConvertible
@@ -71,7 +71,7 @@ private class UserFTS5CustomTokenizer : FTS5CustomTokenizer {
#if SQLITE_ENABLE_FTS5
private class UserFTS5WrapperTokenizer : FTS5WrapperTokenizer {
static let name: String = "UserFTS5WrapperTokenizer"
var wrappedTokenizer: FTS5Tokenizer { preconditionFailure() }
var wrappedTokenizer: any FTS5Tokenizer { preconditionFailure() }
required init(db: Database, arguments: [String]) throws { preconditionFailure() }
func accept(token: String, flags: FTS5TokenFlags, for tokenization: FTS5Tokenization, tokenCallback: (String, FTS5TokenFlags) throws -> ()) throws { preconditionFailure() }
}
@@ -4,7 +4,7 @@ import GRDB
class DatabaseAbortedTransactionTests : GRDBTestCase {
func testReadTransactionAbortedByInterrupt() throws {
func test(_ dbReader: DatabaseReader) throws {
func test(_ dbReader: some DatabaseReader) throws {
let semaphore1 = DispatchSemaphore(value: 0)
let semaphore2 = DispatchSemaphore(value: 0)
@@ -46,7 +46,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase {
}
func testReadTransactionAbortedByInterruptDoesNotPreventFurtherRead() throws {
func test(_ dbReader: DatabaseReader) throws {
func test(_ dbReader: some DatabaseReader) throws {
let semaphore1 = DispatchSemaphore(value: 0)
let semaphore2 = DispatchSemaphore(value: 0)
@@ -316,7 +316,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase {
}
return dbWriter
}
func test(_ dbReader: DatabaseReader) throws {
func test(_ dbReader: some DatabaseReader) throws {
do {
try dbReader.unsafeRead { db in
try db.inTransaction {
+38 -38
View File
@@ -18,7 +18,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateReturningNull() throws {
struct Aggregate : DatabaseAggregate {
func step(_ values: [DatabaseValue]) { }
func finalize() -> DatabaseValueConvertible? { nil }
func finalize() -> (any DatabaseValueConvertible)? { nil }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -31,7 +31,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateReturningInt64() throws {
struct Aggregate : DatabaseAggregate {
func step(_ values: [DatabaseValue]) { }
func finalize() -> DatabaseValueConvertible? { Int64(1) }
func finalize() -> (any DatabaseValueConvertible)? { Int64(1) }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -45,7 +45,7 @@ class DatabaseAggregateTests: GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
struct Aggregate : DatabaseAggregate {
func step(_ values: [DatabaseValue]) { }
func finalize() -> DatabaseValueConvertible? { 1e100 }
func finalize() -> (any DatabaseValueConvertible)? { 1e100 }
}
try dbQueue.inDatabase { db in
let fn = DatabaseFunction("f", argumentCount: 0, aggregate: Aggregate.self)
@@ -57,7 +57,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateReturningString() throws {
struct Aggregate : DatabaseAggregate {
func step(_ values: [DatabaseValue]) { }
func finalize() -> DatabaseValueConvertible? { "foo" }
func finalize() -> (any DatabaseValueConvertible)? { "foo" }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -70,7 +70,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateReturningData() throws {
struct Aggregate : DatabaseAggregate {
func step(_ values: [DatabaseValue]) { }
func finalize() -> DatabaseValueConvertible? {
func finalize() -> (any DatabaseValueConvertible)? {
"foo".data(using: .utf8)
}
}
@@ -85,7 +85,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateReturningCustomValueType() throws {
struct Aggregate : DatabaseAggregate {
func step(_ values: [DatabaseValue]) { }
func finalize() -> DatabaseValueConvertible? { CustomValueType() }
func finalize() -> (any DatabaseValueConvertible)? { CustomValueType() }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -99,11 +99,11 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateArgumentNil() throws {
struct Aggregate : DatabaseAggregate {
var result: DatabaseValueConvertible?
var result: (any DatabaseValueConvertible)?
mutating func step(_ dbValues: [DatabaseValue]) {
result = dbValues[0].isNull
}
func finalize() -> DatabaseValueConvertible? { result }
func finalize() -> (any DatabaseValueConvertible)? { result }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -120,11 +120,11 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateArgumentInt64() throws {
struct Aggregate : DatabaseAggregate {
var result: DatabaseValueConvertible?
var result: (any DatabaseValueConvertible)?
mutating func step(_ dbValues: [DatabaseValue]) {
result = Int64.fromDatabaseValue(dbValues[0])
}
func finalize() -> DatabaseValueConvertible? { result }
func finalize() -> (any DatabaseValueConvertible)? { result }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -138,11 +138,11 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateArgumentDouble() throws {
struct Aggregate : DatabaseAggregate {
var result: DatabaseValueConvertible?
var result: (any DatabaseValueConvertible)?
mutating func step(_ dbValues: [DatabaseValue]) {
result = Double.fromDatabaseValue(dbValues[0])
}
func finalize() -> DatabaseValueConvertible? { result }
func finalize() -> (any DatabaseValueConvertible)? { result }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -156,11 +156,11 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateArgumentString() throws {
struct Aggregate : DatabaseAggregate {
var result: DatabaseValueConvertible?
var result: (any DatabaseValueConvertible)?
mutating func step(_ dbValues: [DatabaseValue]) {
result = String.fromDatabaseValue(dbValues[0])
}
func finalize() -> DatabaseValueConvertible? { result }
func finalize() -> (any DatabaseValueConvertible)? { result }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -173,11 +173,11 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateArgumentBlob() throws {
struct Aggregate : DatabaseAggregate {
var result: DatabaseValueConvertible?
var result: (any DatabaseValueConvertible)?
mutating func step(_ dbValues: [DatabaseValue]) {
result = Data.fromDatabaseValue(dbValues[0])
}
func finalize() -> DatabaseValueConvertible? { result }
func finalize() -> (any DatabaseValueConvertible)? { result }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -191,11 +191,11 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateArgumentCustomValueType() throws {
struct Aggregate : DatabaseAggregate {
var result: DatabaseValueConvertible?
var result: (any DatabaseValueConvertible)?
mutating func step(_ dbValues: [DatabaseValue]) {
result = CustomValueType.fromDatabaseValue(dbValues[0])
}
func finalize() -> DatabaseValueConvertible? { result }
func finalize() -> (any DatabaseValueConvertible)? { result }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -211,7 +211,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateWithoutArgument() throws {
struct Aggregate : DatabaseAggregate {
func step(_ dbValues: [DatabaseValue]) { }
func finalize() -> DatabaseValueConvertible? { "foo" }
func finalize() -> (any DatabaseValueConvertible)? { "foo" }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -232,11 +232,11 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateOfOneArgument() throws {
struct Aggregate : DatabaseAggregate {
var result: DatabaseValueConvertible?
var result: (any DatabaseValueConvertible)?
mutating func step(_ dbValues: [DatabaseValue]) {
result = String.fromDatabaseValue(dbValues[0])?.uppercased()
}
func finalize() -> DatabaseValueConvertible? { result }
func finalize() -> (any DatabaseValueConvertible)? { result }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -259,12 +259,12 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateOfTwoArguments() throws {
struct Aggregate : DatabaseAggregate {
var result: DatabaseValueConvertible?
var result: (any DatabaseValueConvertible)?
mutating func step(_ dbValues: [DatabaseValue]) {
let ints = dbValues.compactMap { Int.fromDatabaseValue($0) }
result = ints.reduce(0, +)
}
func finalize() -> DatabaseValueConvertible? { result }
func finalize() -> (any DatabaseValueConvertible)? { result }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -285,11 +285,11 @@ class DatabaseAggregateTests: GRDBTestCase {
func testVariadicFunction() throws {
struct Aggregate : DatabaseAggregate {
var result: DatabaseValueConvertible?
var result: (any DatabaseValueConvertible)?
mutating func step(_ dbValues: [DatabaseValue]) {
result = dbValues.count
}
func finalize() -> DatabaseValueConvertible? { result }
func finalize() -> (any DatabaseValueConvertible)? { result }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -308,7 +308,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func step(_ dbValues: [DatabaseValue]) throws {
throw DatabaseError(message: "custom error message")
}
func finalize() -> DatabaseValueConvertible? { fatalError() }
func finalize() -> (any DatabaseValueConvertible)? { fatalError() }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -329,7 +329,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func step(_ dbValues: [DatabaseValue]) throws {
throw DatabaseError(resultCode: ResultCode(rawValue: 123))
}
func finalize() -> DatabaseValueConvertible? { fatalError() }
func finalize() -> (any DatabaseValueConvertible)? { fatalError() }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -350,7 +350,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func step(_ dbValues: [DatabaseValue]) throws {
throw DatabaseError(resultCode: ResultCode(rawValue: 123), message: "custom error message")
}
func finalize() -> DatabaseValueConvertible? { fatalError() }
func finalize() -> (any DatabaseValueConvertible)? { fatalError() }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -371,7 +371,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func step(_ dbValues: [DatabaseValue]) throws {
throw NSError(domain: "CustomErrorDomain", code: 123, userInfo: [NSLocalizedDescriptionKey: "custom error message"])
}
func finalize() -> DatabaseValueConvertible? { fatalError() }
func finalize() -> (any DatabaseValueConvertible)? { fatalError() }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -394,7 +394,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateResultThrowingDatabaseErrorWithMessage() throws {
struct Aggregate : DatabaseAggregate {
func step(_ dbValues: [DatabaseValue]) { }
func finalize() throws -> DatabaseValueConvertible? {
func finalize() throws -> (any DatabaseValueConvertible)? {
throw DatabaseError(message: "custom error message")
}
}
@@ -415,7 +415,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateResultThrowingDatabaseErrorWithCode() throws {
struct Aggregate : DatabaseAggregate {
func step(_ dbValues: [DatabaseValue]) { }
func finalize() throws -> DatabaseValueConvertible? {
func finalize() throws -> (any DatabaseValueConvertible)? {
throw DatabaseError(resultCode: ResultCode(rawValue: 123))
}
}
@@ -436,7 +436,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateResultThrowingDatabaseErrorWithMessageAndCode() throws {
struct Aggregate : DatabaseAggregate {
func step(_ dbValues: [DatabaseValue]) { }
func finalize() throws -> DatabaseValueConvertible? {
func finalize() throws -> (any DatabaseValueConvertible)? {
throw DatabaseError(resultCode: ResultCode(rawValue: 123), message: "custom error message")
}
}
@@ -457,7 +457,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func testAggregateResultThrowingCustomError() throws {
struct Aggregate : DatabaseAggregate {
func step(_ dbValues: [DatabaseValue]) { }
func finalize() throws -> DatabaseValueConvertible? {
func finalize() throws -> (any DatabaseValueConvertible)? {
throw NSError(domain: "CustomErrorDomain", code: 123, userInfo: [NSLocalizedDescriptionKey: "custom error message"])
}
}
@@ -487,7 +487,7 @@ class DatabaseAggregateTests: GRDBTestCase {
sum = (sum ?? 0) + int
}
}
func finalize() throws -> DatabaseValueConvertible? { sum }
func finalize() throws -> (any DatabaseValueConvertible)? { sum }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -505,7 +505,7 @@ class DatabaseAggregateTests: GRDBTestCase {
sum = (sum ?? 0) + int
}
}
func finalize() throws -> DatabaseValueConvertible? { sum }
func finalize() throws -> (any DatabaseValueConvertible)? { sum }
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -526,7 +526,7 @@ class DatabaseAggregateTests: GRDBTestCase {
init() { Aggregate.onInit?() }
deinit { Aggregate.onDeinit?() }
func step(_ dbValues: [DatabaseValue]) { }
func finalize() -> DatabaseValueConvertible? { nil }
func finalize() -> (any DatabaseValueConvertible)? { nil }
}
var allocationCount = 0
var aliveCount = 0
@@ -559,7 +559,7 @@ class DatabaseAggregateTests: GRDBTestCase {
func step(_ dbValues: [DatabaseValue]) throws {
throw DatabaseError(message: "boo")
}
func finalize() -> DatabaseValueConvertible? { fatalError() }
func finalize() -> (any DatabaseValueConvertible)? { fatalError() }
}
var allocationCount = 0
var aliveCount = 0
@@ -590,7 +590,7 @@ class DatabaseAggregateTests: GRDBTestCase {
init() { Aggregate.onInit?() }
deinit { Aggregate.onDeinit?() }
func step(_ dbValues: [DatabaseValue]) { }
func finalize() throws -> DatabaseValueConvertible? {
func finalize() throws -> (any DatabaseValueConvertible)? {
throw DatabaseError(message: "boo")
}
}
@@ -62,7 +62,7 @@ class DatabaseDateDecodingStrategyTests: GRDBTestCase {
_ db: Database,
record: T.Type,
date: (T) -> Date?,
databaseValue: DatabaseValueConvertible?,
databaseValue: (any DatabaseValueConvertible)?,
with test: (Date?) -> Void) throws
{
let request = SQLRequest<Void>(sql: "SELECT ? AS date", arguments: [databaseValue])
@@ -79,7 +79,13 @@ class DatabaseDateDecodingStrategyTests: GRDBTestCase {
}
/// test the conversion from a database value to a date with a given strategy
private func test<Strategy: StrategyProvider>(_ db: Database, strategy: Strategy.Type, databaseValue: DatabaseValueConvertible, _ test: (Date) -> Void) throws {
private func test<Strategy: StrategyProvider>(
_ db: Database,
strategy: Strategy.Type,
databaseValue: some DatabaseValueConvertible,
_ test: (Date) -> Void)
throws
{
try self.test(db, record: RecordWithDate<Strategy>.self, date: { $0.date }, databaseValue: databaseValue, with: { test($0!) })
try self.test(db, record: RecordWithOptionalDate<Strategy>.self, date: { $0.date }, databaseValue: databaseValue, with: { test($0!) })
}
@@ -87,7 +87,12 @@ class DatabaseDateEncodingStrategyTests: GRDBTestCase {
}
}
private func test<Strategy: StrategyProvider>(strategy: Strategy.Type, encodesDate date: Date, as value: DatabaseValueConvertible) throws {
private func test<Strategy: StrategyProvider>(
strategy: Strategy.Type,
encodesDate date: Date,
as value: some DatabaseValueConvertible)
throws
{
try test(record: RecordWithDate<Strategy>(date: date), expectedStorage: value.databaseValue.storage)
try test(record: RecordWithOptionalDate<Strategy>(date: date), expectedStorage: value.databaseValue.storage)
}
+14 -14
View File
@@ -18,7 +18,7 @@ class DatabaseReaderTests : GRDBTestCase {
}
return dbWriter
}
func test(_ dbReader: DatabaseReader) throws {
func test(_ dbReader: some DatabaseReader) throws {
let count = try dbReader.read { db in
try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")
}
@@ -41,7 +41,7 @@ class DatabaseReaderTests : GRDBTestCase {
}
return dbWriter
}
func test(_ dbReader: DatabaseReader) async throws {
func test(_ dbReader: some DatabaseReader) async throws {
let count = try await dbReader.read { db in
try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")
}
@@ -57,7 +57,7 @@ class DatabaseReaderTests : GRDBTestCase {
}
func testReadPreventsDatabaseModification() throws {
func test(_ dbReader: DatabaseReader) throws {
func test(_ dbReader: some DatabaseReader) throws {
do {
try dbReader.read { db in
try db.execute(sql: "CREATE TABLE t (id INTEGER PRIMARY KEY)")
@@ -77,7 +77,7 @@ class DatabaseReaderTests : GRDBTestCase {
@available(iOS 13, macOS 10.15, tvOS 13, watchOS 6, *)
func testAsyncAwait_ReadPreventsDatabaseModification() async throws {
func test(_ dbReader: DatabaseReader) async throws {
func test(_ dbReader: some DatabaseReader) async throws {
do {
try await dbReader.read { db in
try db.execute(sql: "CREATE TABLE t (id INTEGER PRIMARY KEY)")
@@ -104,7 +104,7 @@ class DatabaseReaderTests : GRDBTestCase {
}
return dbWriter
}
func test(_ dbReader: DatabaseReader) throws {
func test(_ dbReader: some DatabaseReader) throws {
let count = try dbReader.unsafeRead { db in
try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")
}
@@ -127,7 +127,7 @@ class DatabaseReaderTests : GRDBTestCase {
}
return dbWriter
}
func test(_ dbReader: DatabaseReader) async throws {
func test(_ dbReader: some DatabaseReader) async throws {
let count = try await dbReader.unsafeRead { db in
try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")
}
@@ -151,7 +151,7 @@ class DatabaseReaderTests : GRDBTestCase {
}
return dbWriter
}
func test(_ dbReader: DatabaseReader) throws {
func test(_ dbReader: some DatabaseReader) throws {
let count = try dbReader.unsafeReentrantRead { db in
try Int.fetchOne(db, sql: "SELECT COUNT(*) FROM t")
}
@@ -167,7 +167,7 @@ class DatabaseReaderTests : GRDBTestCase {
}
func testUnsafeReentrantReadIsReentrant() throws {
func test(_ dbReader: DatabaseReader) throws {
func test(_ dbReader: some DatabaseReader) throws {
try dbReader.unsafeReentrantRead { db1 in
try dbReader.unsafeReentrantRead { db2 in
try dbReader.unsafeReentrantRead { db3 in
@@ -187,7 +187,7 @@ class DatabaseReaderTests : GRDBTestCase {
}
func testUnsafeReentrantReadIsReentrantFromWrite() throws {
func test(_ dbWriter: DatabaseWriter) throws {
func test(_ dbWriter: some DatabaseWriter) throws {
try dbWriter.write { db1 in
try dbWriter.unsafeReentrantRead { db2 in
try dbWriter.unsafeReentrantRead { db3 in
@@ -205,7 +205,7 @@ class DatabaseReaderTests : GRDBTestCase {
// MARK: - AsyncRead
func testAsyncRead() throws {
func test(_ dbReader: DatabaseReader) throws {
func test(_ dbReader: some DatabaseReader) throws {
let expectation = self.expectation(description: "updates")
let semaphore = DispatchSemaphore(value: 0)
var count: Int?
@@ -234,7 +234,7 @@ class DatabaseReaderTests : GRDBTestCase {
}
func testAsyncReadPreventsDatabaseModification() throws {
func test(_ dbReader: DatabaseReader) throws {
func test(_ dbReader: some DatabaseReader) throws {
let expectation = self.expectation(description: "updates")
let semaphore = DispatchSemaphore(value: 0)
dbReader.asyncRead { dbResult in
@@ -265,7 +265,7 @@ class DatabaseReaderTests : GRDBTestCase {
// MARK: - Function
func testAddFunction() throws {
func test(_ dbReader: DatabaseReader) throws {
func test(_ dbReader: some DatabaseReader) throws {
let value = try dbReader.read { db -> Int? in
let f = DatabaseFunction("f", argumentCount: 0, pure: true) { _ in 0 }
db.add(function: f)
@@ -285,7 +285,7 @@ class DatabaseReaderTests : GRDBTestCase {
// MARK: - Collation
func testAddCollation() throws {
func test(_ dbReader: DatabaseReader) throws {
func test(_ dbReader: some DatabaseReader) throws {
let value = try dbReader.read { db -> Int? in
let collation = DatabaseCollation("c") { _, _ in .orderedSame }
db.add(collation: collation)
@@ -311,7 +311,7 @@ class DatabaseReaderTests : GRDBTestCase {
}
return dbWriter
}
func test(_ source: DatabaseReader) throws {
func test(_ source: some DatabaseReader) throws {
let dest = try makeDatabaseQueue(configuration: Configuration())
try source.backup(to: dest)
let count = try dest.read { db in
+1 -1
View File
@@ -5,7 +5,7 @@ func insertItem(_ db: Database, name: String) throws {
try db.execute(sql: "INSERT INTO items (name) VALUES (?)", arguments: [name])
}
func fetchAllItemNames(_ dbReader: DatabaseReader) throws -> [String] {
func fetchAllItemNames(_ dbReader: some DatabaseReader) throws -> [String] {
try dbReader.read { db in
try String.fetchAll(db, sql: "SELECT * FROM items ORDER BY name")
}
@@ -53,7 +53,11 @@ class DatabaseUUIDEncodingStrategyTests: GRDBTestCase {
}
}
private func test<Strategy: StrategyProvider>(strategy: Strategy.Type, encodesUUID uuid: UUID, as value: DatabaseValueConvertible) throws {
private func test<Strategy: StrategyProvider>(
strategy: Strategy.Type,
encodesUUID uuid: UUID,
as value: any DatabaseValueConvertible)
throws {
try test(record: RecordWithUUID<Strategy>(uuid: uuid), expectedStorage: value.databaseValue.storage)
try test(record: RecordWithOptionalUUID<Strategy>(uuid: uuid), expectedStorage: value.databaseValue.storage)
}
+1 -1
View File
@@ -19,7 +19,7 @@ extension Book : FetchableRecord {
extension Book : MutablePersistableRecord {
static let databaseTableName = "books"
static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
func encode(to container: inout PersistenceContainer) {
container[.rowID] = id
+1 -1
View File
@@ -19,7 +19,7 @@ extension Book : FetchableRecord {
extension Book : MutablePersistableRecord {
static let databaseTableName = "books"
static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
func encode(to container: inout PersistenceContainer) {
container[.rowID] = id
@@ -6,7 +6,7 @@ import GRDB
// A custom tokenizer that ignores some tokens
private final class StopWordsTokenizer : FTS5CustomTokenizer {
static let name = "stopWords"
let wrappedTokenizer: FTS5Tokenizer
let wrappedTokenizer: any FTS5Tokenizer
let ignoredTokens: [String]
init(db: Database, arguments: [String]) throws {
@@ -62,7 +62,7 @@ private final class StopWordsTokenizer : FTS5CustomTokenizer {
// A custom tokenizer that converts tokens to NFKC so that "fi" can match "fi" (U+FB01: LATIN SMALL LIGATURE FI)
private final class NFKCTokenizer : FTS5CustomTokenizer {
static let name = "nfkc"
let wrappedTokenizer: FTS5Tokenizer
let wrappedTokenizer: any FTS5Tokenizer
init(db: Database, arguments: [String]) throws {
if arguments.isEmpty {
@@ -119,7 +119,7 @@ private final class NFKCTokenizer : FTS5CustomTokenizer {
// A custom tokenizer that defines synonyms
private final class SynonymsTokenizer : FTS5CustomTokenizer {
static let name = "synonyms"
let wrappedTokenizer: FTS5Tokenizer
let wrappedTokenizer: any FTS5Tokenizer
let synonyms: [Set<String>]
init(db: Database, arguments: [String]) throws {
+1 -1
View File
@@ -20,7 +20,7 @@ extension Book : FetchableRecord {
extension Book : MutablePersistableRecord {
static let databaseTableName = "books"
static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
func encode(to container: inout PersistenceContainer) {
container[.rowID] = id
@@ -6,7 +6,7 @@ import GRDB
// A custom wrapper tokenizer that ignores some tokens
private final class StopWordsTokenizer : FTS5WrapperTokenizer {
static let name = "stopWords"
var wrappedTokenizer: FTS5Tokenizer
var wrappedTokenizer: any FTS5Tokenizer
init(db: Database, arguments: [String]) throws {
if arguments.isEmpty {
@@ -29,7 +29,7 @@ private final class StopWordsTokenizer : FTS5WrapperTokenizer {
// A custom wrapper tokenizer that converts tokens to LatinAscii so that "fi" can match "fi" (U+FB01: LATIN SMALL LIGATURE FI), "ß", "ss", and "æ", "ae".
private final class LatinAsciiTokenizer : FTS5WrapperTokenizer {
static let name = "latinascii"
let wrappedTokenizer: FTS5Tokenizer
let wrappedTokenizer: any FTS5Tokenizer
init(db: Database, arguments: [String]) throws {
wrappedTokenizer = try db.makeTokenizer(.unicode61())
@@ -46,7 +46,7 @@ private final class LatinAsciiTokenizer : FTS5WrapperTokenizer {
// A custom wrapper tokenizer that defines synonyms
private final class SynonymsTokenizer : FTS5WrapperTokenizer {
static let name = "synonyms"
let wrappedTokenizer: FTS5Tokenizer
let wrappedTokenizer: any FTS5Tokenizer
let synonyms: [Set<String>] = [["first", "1st"]]
init(db: Database, arguments: [String]) throws {
@@ -87,7 +87,7 @@ private final class SynonymsTokenizer : FTS5WrapperTokenizer {
class CustomizedUnicode61WrappingTokenizer: FTS5WrapperTokenizer {
static let name = "custom_unicode61"
let wrappedTokenizer: FTS5Tokenizer
let wrappedTokenizer: any FTS5Tokenizer
required init(db: Database, arguments: [String]) throws {
wrappedTokenizer = try db.makeTokenizer(.unicode61(diacritics: .removeLegacy, separators: ["X"]))
+1 -1
View File
@@ -2,7 +2,7 @@ import XCTest
import GRDB
class FoundationNSUUIDTests: GRDBTestCase {
private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: NSUUID?) throws {
private func assert(_ value: (any DatabaseValueConvertible)?, isDecodedAs expectedUUID: NSUUID?) throws {
try makeDatabaseQueue().read { db in
if let expectedUUID {
let decodedUUID = try NSUUID.fetchOne(db, sql: "SELECT ?", arguments: [value])
+1 -1
View File
@@ -3,7 +3,7 @@ import Foundation
import GRDB
class FoundationUUIDTests: GRDBTestCase {
private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: UUID?) throws {
private func assert(_ value: (any DatabaseValueConvertible)?, isDecodedAs expectedUUID: UUID?) throws {
try makeDatabaseQueue().read { db in
if let expectedUUID {
let decodedUUID = try UUID.fetchOne(db, sql: "SELECT ?", arguments: [value])
+21 -3
View File
@@ -147,19 +147,37 @@ class GRDBTestCase: XCTestCase {
}
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
func assertEqualSQL<Request: FetchRequest>(_ db: Database, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws {
func assertEqualSQL(
_ db: Database,
_ request: some FetchRequest,
_ sql: String,
file: StaticString = #file,
line: UInt = #line)
throws
{
try request.makeStatement(db).makeCursor().next()
assertEqualSQL(lastSQLQuery!, sql, file: file, line: line)
}
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
func assertEqualSQL<Request: FetchRequest>(_ databaseReader: DatabaseReader, _ request: Request, _ sql: String, file: StaticString = #file, line: UInt = #line) throws {
func assertEqualSQL(
_ databaseReader: some DatabaseReader,
_ request: some FetchRequest,
_ sql: String,
file: StaticString = #file,
line: UInt = #line)
throws
{
try databaseReader.unsafeRead { db in
try assertEqualSQL(db, request, sql, file: file, line: line)
}
}
func sql<Request: FetchRequest>(_ databaseReader: DatabaseReader, _ request: Request) -> String {
func sql(
_ databaseReader: some DatabaseReader,
_ request: some FetchRequest)
-> String
{
try! databaseReader.unsafeRead { db in
try request.makeStatement(db).makeCursor().next()
return lastSQLQuery!
+1 -1
View File
@@ -50,7 +50,7 @@ private struct T2: Codable, FetchableRecord, TableRecord {
private struct T3: Codable, FetchableRecord, TableRecord {
static let databaseTableName = "t3"
static let databaseSelection: [SQLSelectable] = [Column("t1id"), Column("name")]
static let databaseSelection: [any SQLSelectable] = [Column("t1id"), Column("name")]
var t1id: Int64
var name: String
}
@@ -185,7 +185,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
"SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) NOT IN ('arthur', 'barbara')")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [SQLExpressible]).contains(Col.name.collating(.nocase)))),
sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [any SQLExpressible]).contains(Col.name.collating(.nocase)))),
"SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')")
// Sequence.contains(): IN operator
@@ -239,7 +239,7 @@ class QueryInterfaceExpressionsTests: GRDBTestCase {
"SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) NOT IN ('arthur', 'barbara')")
XCTAssertEqual(
sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [SQLExpressible]).contains(Col.name).collating(.nocase))),
sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [any SQLExpressible]).contains(Col.name).collating(.nocase))),
"SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')")
// Sequence.contains(): IN operator
@@ -14,14 +14,14 @@ class RecordPersistenceConflictPolicyTests: GRDBTestCase {
func testDefaultPersistenceConflictPolicy() {
let record = RecordWithoutPersistenceConflictPolicy()
let policy = type(of: record as MutablePersistableRecord).persistenceConflictPolicy
let policy = type(of: record).persistenceConflictPolicy
XCTAssertEqual(policy.conflictResolutionForInsert, .abort)
XCTAssertEqual(policy.conflictResolutionForUpdate, .abort)
}
func testConfigurablePersistenceConflictPolicy() {
let record = RecordWithPersistenceConflictPolicy()
let policy = type(of: record as MutablePersistableRecord).persistenceConflictPolicy
let policy = type(of: record).persistenceConflictPolicy
XCTAssertEqual(policy.conflictResolutionForInsert, .fail)
XCTAssertEqual(policy.conflictResolutionForUpdate, .ignore)
}
@@ -27,7 +27,7 @@ private class Person : Record, Hashable {
// Record
override static var databaseSelection: [SQLSelectable] {
override static var databaseSelection: [any SQLSelectable] {
[AllColumns(), Column.rowID]
}
+3 -3
View File
@@ -27,7 +27,7 @@ class RowFromDictionaryTests : RowTestCase {
}
func testRowValueAtIndex() {
let dictionary: [String: DatabaseValueConvertible?] = ["a": 0, "b": 1, "c": 2]
let dictionary: [String: (any DatabaseValueConvertible)?] = ["a": 0, "b": 1, "c": 2]
let row = Row(dictionary)
let aIndex = dictionary.distance(from: dictionary.startIndex, to: dictionary.index(forKey: "a")!)
@@ -123,7 +123,7 @@ class RowFromDictionaryTests : RowTestCase {
}
func testRowDatabaseValueAtIndex() throws {
let dictionary: [String: DatabaseValueConvertible?] = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)]
let dictionary: [String: (any DatabaseValueConvertible)?] = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)]
let row = Row(dictionary)
let nullIndex = dictionary.distance(from: dictionary.startIndex, to: dictionary.index(forKey: "null")!)
@@ -140,7 +140,7 @@ class RowFromDictionaryTests : RowTestCase {
}
func testRowDatabaseValueNamed() throws {
let dictionary: [String: DatabaseValueConvertible?] = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)]
let dictionary: [String: (any DatabaseValueConvertible)?] = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)]
let row = Row(dictionary)
guard case .null = (row["null"] as DatabaseValue).storage else { XCTFail(); return }
+98 -28
View File
@@ -220,7 +220,7 @@ extension SQLLiteralTests {
do {
// Existential
let query: SQL = """
SELECT \(AllColumns() as SQLSelectable)
SELECT \(AllColumns() as any SQLSelectable)
FROM player
"""
@@ -234,7 +234,7 @@ extension SQLLiteralTests {
do {
// Existential
let query: SQL = """
SELECT \(nil as SQLSelectable?)
SELECT \(nil as (any SQLSelectable)?)
"""
let (sql, arguments) = try query.build(db)
@@ -293,7 +293,7 @@ extension SQLLiteralTests {
do {
// Existential
let query: SQL = """
INSERT INTO \(tableOf: Player() as TableRecord) DEFAULT VALUES
INSERT INTO \(tableOf: Player() as any TableRecord) DEFAULT VALUES
"""
let (sql, arguments) = try query.build(db)
@@ -309,7 +309,7 @@ extension SQLLiteralTests {
try makeDatabaseQueue().inDatabase { db in
struct Player: TableRecord { }
struct AltPlayer: TableRecord {
static let databaseSelection: [SQLSelectable] = [Column("id"), Column("name")]
static let databaseSelection: [any SQLSelectable] = [Column("id"), Column("name")]
}
do {
let query: SQL = """
@@ -499,7 +499,7 @@ extension SQLLiteralTests {
try makeDatabaseQueue().inDatabase { db in
let set: Set = [1]
let array = ["foo", "bar", "baz"]
let expressions: [SQLExpressible] = [Column("a"), Column("b") + 2]
let expressions: [any SQLExpressible] = [Column("a"), Column("b") + 2]
let query: SQL = """
SELECT * FROM player
WHERE teamId IN \(set)
@@ -742,8 +742,21 @@ extension SQLLiteralTests {
do {
// Here we test that users can define functions that return
// literal expressions.
func date(_ value: SQLExpressible) -> SQLExpression {
// literal expressions (existential variant).
func date(_ value: any SQLExpressible) -> SQLExpression {
SQL("DATE(\(value))").sqlExpression
}
let createdAt = Column("createdAt")
let request = Player.filter(date(createdAt) == "2020-01-23")
try assertEqualSQL(db, request, """
SELECT * FROM "player" WHERE (DATE("createdAt")) = '2020-01-23'
""")
}
do {
// Here we test that users can define functions that return
// literal expressions (generic variant).
func date(_ value: some SQLExpressible) -> SQLExpression {
SQL("DATE(\(value))").sqlExpression
}
let createdAt = Column("createdAt")
@@ -756,8 +769,22 @@ extension SQLLiteralTests {
do {
// Here we test that users can still define functions that
// return literal expressions with the previously
// supported technique.
func date(_ value: SQLExpressible) -> SQLExpression {
// supported technique (existential variant).
func date(_ value: any SQLExpressible) -> SQLExpression {
SQL("DATE(\(value.sqlExpression))").sqlExpression
}
let createdAt = Column("createdAt")
let request = Player.filter(date(createdAt) == "2020-01-23")
try assertEqualSQL(db, request, """
SELECT * FROM "player" WHERE (DATE("createdAt")) = '2020-01-23'
""")
}
do {
// Here we test that users can still define functions that
// return literal expressions with the previously
// supported technique (generic variant).
func date(_ value: some SQLExpressible) -> SQLExpression {
SQL("DATE(\(value.sqlExpression))").sqlExpression
}
let createdAt = Column("createdAt")
@@ -800,10 +827,15 @@ extension SQLLiteralTests {
func testProtocolResolution() throws {
// SQL can feed ordering, selection, and expressions.
acceptOrderingTerm(SQL(""))
acceptSelectable(SQL(""))
acceptSpecificExpressible(SQL(""))
acceptExpressible(SQL(""))
acceptOrderingTerm_generic(SQL(""))
acceptSelectable_generic(SQL(""))
acceptSpecificExpressible_generic(SQL(""))
acceptExpressible_generic(SQL(""))
acceptOrderingTerm_existential(SQL(""))
acceptSelectable_existential(SQL(""))
acceptSpecificExpressible_existential(SQL(""))
acceptExpressible_existential(SQL(""))
// SQL can build complex expressions and orderings
_ = SQL("") + 1
@@ -812,18 +844,24 @@ extension SQLLiteralTests {
// Swift String literals are interpreted as String, even when SQL
// is an accepted type.
//
// should not compile: XCTAssertEqual(acceptOrderingTerm(""), String(describing: String.self))
// should not compile: XCTAssertEqual(acceptSelectable(""), String(describing: String.self))
// should not compile: XCTAssertEqual(acceptSpecificExpressible(""), String(describing: String.self))
XCTAssertEqual(acceptExpressible(""), String(describing: String.self))
// should not compile: XCTAssertEqual(acceptOrderingTerm_generic(""), String(describing: String.self))
// should not compile: XCTAssertEqual(acceptSelectable_generic(""), String(describing: String.self))
// should not compile: XCTAssertEqual(acceptSpecificExpressible_generic(""), String(describing: String.self))
XCTAssertEqual(acceptExpressible_generic(""), String(describing: String.self))
// should not compile: XCTAssertEqual(acceptOrderingTerm_existential(""), String(describing: String.self))
// should not compile: XCTAssertEqual(acceptSelectable_existential(""), String(describing: String.self))
// should not compile: XCTAssertEqual(acceptSpecificExpressible_existential(""), String(describing: String.self))
XCTAssertEqual(acceptExpressible_existential(""), String(describing: String.self))
// When a literal can be interpreted as an ordering, a selection, or an
// expression, then the expression interpretation is favored.
// This test targets TableAlias subscript.
//
// should not compile: XCTAssertEqual(overloaded(""), "a")
XCTAssertEqual(overloaded(SQL("")), "SQLSpecificExpressible")
// should not compile: XCTAssertEqual(overloaded_generic(""), "a")
XCTAssertEqual(overloaded_generic(SQL("")), "SQLSpecificExpressible")
// should not compile: XCTAssertEqual(overloaded_existential(""), "a")
XCTAssertEqual(overloaded_existential(SQL("")), "SQLSpecificExpressible")
// In practice:
try makeDatabaseQueue().write { db in
struct Player: TableRecord { }
@@ -850,33 +888,65 @@ extension SQLLiteralTests {
// Support for testProtocolResolution()
@discardableResult
private func acceptOrderingTerm(_ x: SQLOrderingTerm) -> String {
private func acceptOrderingTerm_generic(_ x: some SQLOrderingTerm) -> String {
String(describing: type(of: x))
}
@discardableResult
private func acceptSelectable(_ x: SQLSelectable) -> String {
private func acceptSelectable_generic(_ x: some SQLSelectable) -> String {
String(describing: type(of: x))
}
@discardableResult
private func acceptSpecificExpressible(_ x: SQLSpecificExpressible) -> String {
private func acceptSpecificExpressible_generic(_ x: some SQLSpecificExpressible) -> String {
String(describing: type(of: x))
}
@discardableResult
private func acceptExpressible(_ x: SQLExpressible) -> String {
private func acceptExpressible_generic(_ x: some SQLExpressible) -> String {
String(describing: type(of: x))
}
private func overloaded(_ x: SQLOrderingTerm) -> String {
private func overloaded_generic(_ x: some SQLOrderingTerm) -> String {
"SQLOrderingTerm"
}
private func overloaded(_ x: SQLSelectable) -> String {
private func overloaded_generic(_ x: some SQLSelectable) -> String {
"SQLSelectable"
}
private func overloaded(_ x: SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> String {
private func overloaded_generic(_ x: some SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> String {
"SQLSpecificExpressible"
}
@discardableResult
private func acceptOrderingTerm_existential(_ x: any SQLOrderingTerm) -> String {
String(describing: type(of: x))
}
@discardableResult
private func acceptSelectable_existential(_ x: any SQLSelectable) -> String {
String(describing: type(of: x))
}
@discardableResult
private func acceptSpecificExpressible_existential(_ x: any SQLSpecificExpressible) -> String {
String(describing: type(of: x))
}
@discardableResult
private func acceptExpressible_existential(_ x: any SQLExpressible) -> String {
String(describing: type(of: x))
}
private func overloaded_existential(_ x: any SQLOrderingTerm) -> String {
"SQLOrderingTerm"
}
private func overloaded_existential(_ x: any SQLSelectable) -> String {
"SQLSelectable"
}
private func overloaded_existential(_ x: any SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> String {
"SQLSpecificExpressible"
}
+2 -2
View File
@@ -98,7 +98,7 @@ class SelectStatementTests : GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < :age")
let ageDicts: [[String: DatabaseValueConvertible?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]]
let ageDicts: [[String: (any DatabaseValueConvertible)?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]]
let counts = try ageDicts.map { dic -> Int in
// Make sure we don't trigger a failible initializer
let arguments: StatementArguments = StatementArguments(dic)
@@ -112,7 +112,7 @@ class SelectStatementTests : GRDBTestCase {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM persons WHERE age < :age")
let ageDicts: [[String: DatabaseValueConvertible?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]]
let ageDicts: [[String: (any DatabaseValueConvertible)?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]]
let counts = try ageDicts.map { ageDict -> Int in
statement.arguments = StatementArguments(ageDict)
return try Int.fetchOne(statement)!
@@ -81,7 +81,7 @@ class StatementArgumentsTests: GRDBTestCase {
try dbQueue.inDatabase { db in
let name = "Arthur"
let age = 42
let arguments = StatementArguments([name, age] as [DatabaseValueConvertible?])
let arguments = StatementArguments([name, age] as [(any DatabaseValueConvertible)?])
let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)")
updateStatement.arguments = arguments
@@ -101,7 +101,7 @@ class StatementArgumentsTests: GRDBTestCase {
try dbQueue.inDatabase { db in
let name = "Arthur"
let age = 42
let arguments = StatementArguments([name, age] as [DatabaseValueConvertible?])
let arguments = StatementArguments([name, age] as [(any DatabaseValueConvertible)?])
let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)")
try updateStatement.setArguments(arguments)
@@ -139,7 +139,7 @@ class StatementArgumentsTests: GRDBTestCase {
try dbQueue.inDatabase { db in
let name = "Arthur"
let age = 42
let arguments = StatementArguments([name, age] as [DatabaseValueConvertible?])
let arguments = StatementArguments([name, age] as [(any DatabaseValueConvertible)?])
let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (?, ?)")
updateStatement.setUncheckedArguments(arguments)
@@ -232,7 +232,7 @@ class StatementArgumentsTests: GRDBTestCase {
try dbQueue.inDatabase { db in
let name = "Arthur"
let age = 42
let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?])
let arguments = StatementArguments(["name": name, "age": age] as [String: (any DatabaseValueConvertible)?])
let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:name, :age)")
updateStatement.arguments = arguments
@@ -252,7 +252,7 @@ class StatementArgumentsTests: GRDBTestCase {
try dbQueue.inDatabase { db in
let name = "Arthur"
let age = 42
let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?])
let arguments = StatementArguments(["name": name, "age": age] as [String: (any DatabaseValueConvertible)?])
let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:name, :age)")
try updateStatement.setArguments(arguments)
@@ -290,7 +290,7 @@ class StatementArgumentsTests: GRDBTestCase {
try dbQueue.inDatabase { db in
let name = "Arthur"
let age = 42
let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?])
let arguments = StatementArguments(["name": name, "age": age] as [String: (any DatabaseValueConvertible)?])
let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, age) VALUES (:name, :age)")
updateStatement.setUncheckedArguments(arguments)
@@ -392,7 +392,7 @@ class StatementArgumentsTests: GRDBTestCase {
try dbQueue.inDatabase { db in
let name = "Arthur"
let age = 42
let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?])
let arguments = StatementArguments(["name": name, "age": age] as [String: (any DatabaseValueConvertible)?])
let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)")
updateStatement.arguments = arguments
@@ -412,7 +412,7 @@ class StatementArgumentsTests: GRDBTestCase {
try dbQueue.inDatabase { db in
let name = "Arthur"
let age = 42
let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?])
let arguments = StatementArguments(["name": name, "age": age] as [String: (any DatabaseValueConvertible)?])
let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)")
try updateStatement.setArguments(arguments)
@@ -450,7 +450,7 @@ class StatementArgumentsTests: GRDBTestCase {
try dbQueue.inDatabase { db in
let name = "Arthur"
let age = 42
let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?])
let arguments = StatementArguments(["name": name, "age": age] as [String: (any DatabaseValueConvertible)?])
let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)")
updateStatement.setUncheckedArguments(arguments)
+2 -2
View File
@@ -103,7 +103,7 @@ class TableRecordTests: GRDBTestCase {
func testExtendedDatabaseSelection() throws {
struct Record: TableRecord {
static let databaseTableName = "t1"
static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -116,7 +116,7 @@ class TableRecordTests: GRDBTestCase {
func testRestrictedDatabaseSelection() throws {
struct Record: TableRecord {
static let databaseTableName = "t1"
static let databaseSelection: [SQLSelectable] = [Column("a"), Column("b")]
static let databaseSelection: [any SQLSelectable] = [Column("a"), Column("b")]
}
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
@@ -121,7 +121,7 @@ extension Artwork : FetchableRecord, PersistableRecord {
}
class TransactionObserverTests: GRDBTestCase {
private func setupArtistDatabase(in dbWriter: DatabaseWriter) throws {
private func setupArtistDatabase(in dbWriter: some DatabaseWriter) throws {
try dbWriter.write { db in
try db.execute(sql: """
CREATE TABLE artists (
+4 -4
View File
@@ -52,7 +52,7 @@ class UpdateStatementTests : GRDBTestCase {
try dbQueue.inTransaction { db in
let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (?, ?)")
let persons: [[DatabaseValueConvertible?]] = [
let persons: [[(any DatabaseValueConvertible)?]] = [
["Arthur", 41],
["Barbara", nil],
]
@@ -79,7 +79,7 @@ class UpdateStatementTests : GRDBTestCase {
try dbQueue.inTransaction { db in
let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (?, ?)")
let persons: [[DatabaseValueConvertible?]] = [
let persons: [[(any DatabaseValueConvertible)?]] = [
["Arthur", 41],
["Barbara", nil],
]
@@ -107,7 +107,7 @@ class UpdateStatementTests : GRDBTestCase {
try dbQueue.inTransaction { db in
let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)")
let persons: [[String: DatabaseValueConvertible?]] = [
let persons: [[String: (any DatabaseValueConvertible)?]] = [
["name": "Arthur", "age": 41],
["name": "Barbara", "age": nil],
]
@@ -134,7 +134,7 @@ class UpdateStatementTests : GRDBTestCase {
try dbQueue.inTransaction { db in
let statement = try db.makeStatement(sql: "INSERT INTO persons (name, age) VALUES (:name, :age)")
let persons: [[String: DatabaseValueConvertible?]] = [
let persons: [[String: (any DatabaseValueConvertible)?]] = [
["name": "Arthur", "age": 41],
["name": "Barbara", "age": nil],
]
@@ -11,7 +11,7 @@ class ValueObservationPrintTests: GRDBTestCase {
}
/// Helps dealing with various SQLite versions
private func region(sql: String, in dbReader: DatabaseReader) throws -> String {
private func region(sql: String, in dbReader: some DatabaseReader) throws -> String {
try dbReader.read { db in
try db
.makeStatement(sql: sql)
@@ -436,13 +436,17 @@ class ValueObservationPrintTests: GRDBTestCase {
onChange: { _ in expectation.fulfill() })
withExtendedLifetime(cancellable) {
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(logger.strings, [
"start",
"fetch",
"value: nil",
// Order of events may not be stable, because the first
// "value: nil" is notified concurrently (from the reduce queue)
// with the first "database did change" (from the writer queue).
// That's why we test the sorted output.
XCTAssertEqual(logger.strings.sorted(), [
"database did change",
"fetch",
"fetch",
"start",
"tracked region: \(expectedRegion)",
"value: nil",
"value: nil"])
}
}
@@ -567,7 +567,7 @@ extension GRDBTestCase {
func assertValueObservation<Reducer: ValueReducer, Failure: Error>(
_ observation: ValueObservation<Reducer>,
fails testFailure: (Failure, DatabaseWriter) throws -> Void,
fails testFailure: (Failure, any DatabaseWriter) throws -> Void,
setup: (Database) throws -> Void,
file: StaticString = #file,
line: UInt = #line)
+4 -4
View File
@@ -542,7 +542,7 @@ class ValueObservationTests: GRDBTestCase {
}
// Start observation and deallocate cancellable after second change
var cancellable: DatabaseCancellable?
var cancellable: (any DatabaseCancellable)?
cancellable = observation.start(
in: dbQueue,
onError: { error in XCTFail("Unexpected error: \(error)") },
@@ -588,7 +588,7 @@ class ValueObservationTests: GRDBTestCase {
}
// Start observation and cancel cancellable after second change
var cancellable: DatabaseCancellable!
var cancellable: (any DatabaseCancellable)!
cancellable = observation.start(
in: dbQueue,
onError: { error in XCTFail("Unexpected error: \(error)") },
@@ -626,7 +626,7 @@ class ValueObservationTests: GRDBTestCase {
notificationExpectation.expectedFulfillmentCount = 2
do {
var cancellable: DatabaseCancellable? = nil
var cancellable: (any DatabaseCancellable)? = nil
_ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning
var shouldStopObservation = false
let observation = ValueObservation(
@@ -670,7 +670,7 @@ class ValueObservationTests: GRDBTestCase {
notificationExpectation.expectedFulfillmentCount = 2
do {
var cancellable: DatabaseCancellable? = nil
var cancellable: (any DatabaseCancellable)? = nil
_ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning
var shouldStopObservation = false
let observation = ValueObservation(
@@ -29,7 +29,7 @@ private struct Item: Codable, FetchableRecord, PersistableRecord {
i9 = row[9]
}
static let databaseSelection: [SQLSelectable] = [
static let databaseSelection: [any SQLSelectable] = [
Column("i0"),
Column("i1"),
Column("i2"),