mirror of
https://github.com/groue/GRDB.swift
synced 2026-12-06 05:28:44 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9318693fe4 |
No files matched your search
+12
-32
@@ -38,18 +38,6 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-12
|
||||
destination: "platform=macOS"
|
||||
name: "macOS"
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-12
|
||||
destination: "OS=16.2,name=iPhone 14"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-12
|
||||
destination: "OS=16.1,name=Apple TV"
|
||||
name: "tvOS"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
destination: "platform=macOS"
|
||||
@@ -58,6 +46,10 @@ jobs:
|
||||
runsOn: macOS-12
|
||||
destination: "OS=16.1,name=iPhone 14"
|
||||
name: "iOS"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
destination: "OS=16.1,name=Apple TV"
|
||||
name: "tvOS"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
destination: "platform=macOS"
|
||||
@@ -80,9 +72,6 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.2.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.2"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.1"
|
||||
@@ -103,9 +92,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.2.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.2"
|
||||
name: "Xcode 14.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -120,12 +109,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.2.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.2"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
name: "Xcode 14.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -140,12 +126,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.2.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.2"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
name: "Xcode 14.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
@@ -160,12 +143,9 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- xcode: "Xcode_14.2.app"
|
||||
- xcode: "Xcode_14.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.2"
|
||||
- xcode: "Xcode_14.0.1.app"
|
||||
runsOn: macOS-12
|
||||
name: "Xcode 14.0.1"
|
||||
name: "Xcode 14.1"
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: ${{ matrix.name }}
|
||||
|
||||
+1
-14
@@ -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.2](#6102)
|
||||
- `6.10.x` Releases - [6.10.0](#6100)
|
||||
- `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,19 +108,6 @@ 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)
|
||||
|
||||
- **Fixed**: [#1357](https://github.com/groue/GRDB.swift/pull/1357) `QueryInterfaceRequest.fetchCount` no longer executes invalid SQL queries for some requests.
|
||||
|
||||
## 6.10.0
|
||||
|
||||
Released March 20, 2023 • [diff](https://github.com/groue/GRDB.swift/compare/v6.9.2...v6.10.0)
|
||||
|
||||
@@ -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]
|
||||
- [Recommended Practices for Designing Record Types] - in this general guide about records, check out the "Associations" chapter.
|
||||
- [Good Practices for Designing Record Types] - in this general guide about records, check out the "Compose Records" chapter.
|
||||
|
||||
|
||||
## The Structure of a Joined Request
|
||||
@@ -2860,7 +2860,7 @@ extension DerivableRequest<Book> {
|
||||
}
|
||||
```
|
||||
|
||||
See [Recommended Practices for Designing Record Types] for more information.
|
||||
See [Good 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
|
||||
[Recommended Practices for Designing Record Types]: https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices
|
||||
[Good Practices for Designing Record Types]: GoodPracticesForDesigningRecordTypes.md
|
||||
[regular aggregating methods]: ../README.md#fetching-aggregated-values
|
||||
[Record class]: ../README.md#record-class
|
||||
[EncodableRecord]: ../README.md#persistablerecord-protocol
|
||||
|
||||
-7
@@ -61,13 +61,6 @@
|
||||
ReferencedContainer = "container:GRDBAsyncDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "SQL_TRACE"
|
||||
value = "1"
|
||||
isEnabled = "NO">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,29 +1,12 @@
|
||||
import Foundation
|
||||
import GRDB
|
||||
import os.log
|
||||
|
||||
/// A database of players.
|
||||
/// AppDatabase lets the application access the database.
|
||||
///
|
||||
/// 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)
|
||||
/// ```
|
||||
/// It applies the pratices recommended at
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
struct AppDatabase {
|
||||
/// Creates an `AppDatabase`, and makes sure the database schema
|
||||
/// is ready.
|
||||
///
|
||||
/// - important: Create the `DatabaseWriter` with a configuration
|
||||
/// returned by ``makeConfiguration(_:)``.
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: any DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
@@ -36,67 +19,18 @@ 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
|
||||
@@ -118,7 +52,6 @@ extension 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
|
||||
@@ -194,8 +127,8 @@ extension AppDatabase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static let uiTestPlayers = [
|
||||
|
||||
static let uiTestPlayers = [
|
||||
Player(id: nil, name: "Arthur", score: 5),
|
||||
Player(id: nil, name: "Barbara", score: 6),
|
||||
Player(id: nil, name: "Craig", score: 8),
|
||||
@@ -204,7 +137,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,31 +7,26 @@ extension AppDatabase {
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// 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)
|
||||
|
||||
// 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)
|
||||
|
||||
// Support for tests: delete the database if requested
|
||||
if CommandLine.arguments.contains("-reset") {
|
||||
try? fileManager.removeItem(at: directoryURL)
|
||||
try? fileManager.removeItem(at: folderURL)
|
||||
}
|
||||
|
||||
// Create the database folder if needed
|
||||
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
|
||||
// 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())
|
||||
// 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)
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
@@ -64,7 +59,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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try! DatabaseQueue()
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
|
||||
@@ -69,7 +69,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
|
||||
// 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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 [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- How to feed SwiftUI previews with a transient database.
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
-7
@@ -61,13 +61,6 @@
|
||||
ReferencedContainer = "container:GRDBCombineDemo.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "SQL_TRACE"
|
||||
value = "1"
|
||||
isEnabled = "NO">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,29 +1,13 @@
|
||||
import Combine
|
||||
import Foundation
|
||||
import GRDB
|
||||
import os.log
|
||||
|
||||
/// A database of players.
|
||||
/// AppDatabase lets the application access the database.
|
||||
///
|
||||
/// 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)
|
||||
/// ```
|
||||
/// It applies the pratices recommended at
|
||||
/// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
struct AppDatabase {
|
||||
/// Creates an `AppDatabase`, and makes sure the database schema
|
||||
/// is ready.
|
||||
///
|
||||
/// - important: Create the `DatabaseWriter` with a configuration
|
||||
/// returned by ``makeConfiguration(_:)``.
|
||||
/// Creates an `AppDatabase`, and make sure the database schema is ready.
|
||||
init(_ dbWriter: any DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
@@ -36,67 +20,18 @@ 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
|
||||
@@ -118,7 +53,6 @@ extension 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
|
||||
@@ -194,8 +128,8 @@ extension AppDatabase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static let uiTestPlayers = [
|
||||
|
||||
static let uiTestPlayers = [
|
||||
Player(id: nil, name: "Arthur", score: 5),
|
||||
Player(id: nil, name: "Barbara", score: 6),
|
||||
Player(id: nil, name: "Craig", score: 8),
|
||||
@@ -204,7 +138,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,31 +7,26 @@ extension AppDatabase {
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// 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)
|
||||
|
||||
// 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)
|
||||
|
||||
// Support for tests: delete the database if requested
|
||||
if CommandLine.arguments.contains("-reset") {
|
||||
try? fileManager.removeItem(at: directoryURL)
|
||||
try? fileManager.removeItem(at: folderURL)
|
||||
}
|
||||
|
||||
// Create the database folder if needed
|
||||
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
||||
try fileManager.createDirectory(at: folderURL, withIntermediateDirectories: true)
|
||||
|
||||
// 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())
|
||||
// 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)
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
@@ -64,7 +59,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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try! DatabaseQueue()
|
||||
return try! AppDatabase(dbQueue)
|
||||
}
|
||||
|
||||
|
||||
@@ -69,7 +69,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
|
||||
// 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
let appDatabase = try AppDatabase(dbQueue)
|
||||
var player = Player(id: nil, name: "Arthur", score: 100)
|
||||
try dbQueue.write { db in
|
||||
|
||||
+2
-2
@@ -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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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 [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
- How to feed SwiftUI previews with a transient database.
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
-7
@@ -61,13 +61,6 @@
|
||||
ReferencedContainer = "container:GRDBDemoiOS.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
<EnvironmentVariables>
|
||||
<EnvironmentVariable
|
||||
key = "SQL_TRACE"
|
||||
value = "1"
|
||||
isEnabled = "NO">
|
||||
</EnvironmentVariable>
|
||||
</EnvironmentVariables>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
|
||||
@@ -1,28 +1,11 @@
|
||||
import GRDB
|
||||
import os.log
|
||||
|
||||
/// `AppDatabase` lets the application access the database.
|
||||
/// AppDatabase lets the application access the database.
|
||||
///
|
||||
/// 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(_:)``.
|
||||
/// 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.
|
||||
init(_ dbWriter: any DatabaseWriter) throws {
|
||||
self.dbWriter = dbWriter
|
||||
try migrator.migrate(dbWriter)
|
||||
@@ -35,67 +18,18 @@ 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
|
||||
@@ -117,7 +51,6 @@ extension 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,24 +7,19 @@ extension AppDatabase {
|
||||
|
||||
private static func makeShared() -> AppDatabase {
|
||||
do {
|
||||
// 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)
|
||||
// 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)
|
||||
|
||||
// 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())
|
||||
// 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)
|
||||
|
||||
// Create the AppDatabase
|
||||
let appDatabase = try AppDatabase(dbPool)
|
||||
|
||||
@@ -68,7 +68,8 @@ extension Player: Codable, FetchableRecord, MutablePersistableRecord {
|
||||
|
||||
/// Define some player requests used by the application.
|
||||
///
|
||||
/// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/README.md#requests>
|
||||
/// See <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md>
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
|
||||
// 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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(configuration: AppDatabase.makeConfiguration())
|
||||
let dbQueue = try DatabaseQueue()
|
||||
_ = 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 table view with [ValueObservation](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/valueobservation).
|
||||
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
- How to apply the recommendations of [Good Practices for Designing Record Types](../../GoodPracticesForDesigningRecordTypes.md).
|
||||
|
||||
**Files of interest:**
|
||||
|
||||
|
||||
@@ -1,4 +1,836 @@
|
||||
Good Practices for Designing Record Types
|
||||
=========================================
|
||||
|
||||
This guide [has moved](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
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
|
||||
@@ -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 [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) 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 [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) and [Associations](AssociationsBasics.md).
|
||||
|
||||
### FetchRequest
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ To release a new GRDB version:
|
||||
- Check tag authors: `git for-each-ref --format '%(refname) %(authorname)' refs/tags`
|
||||
- Push to the master & development branch
|
||||
- `pod trunk push --allow-warnings GRDB.swift.podspec`
|
||||
- Update https://github.com/groue/WWDCCompanion
|
||||
- Update [performance comparison](https://github.com/groue/GRDB.swift/wiki/Performance):
|
||||
|
||||
`make test_performance | Tests/parsePerformanceTests.rb | Tests/generatePerformanceReport.rb`
|
||||
@@ -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 [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for some practical advice.
|
||||
See [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md) 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 [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices).
|
||||
For practical advice on designing the database access layer of your application, see the [Good Practices for Designing Record Types](GoodPracticesForDesigningRecordTypes.md).
|
||||
|
||||
|
||||
### Never pay for using raw SQL
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
Pod::Spec.new do |s|
|
||||
s.name = 'GRDB.swift'
|
||||
s.version = '6.10.2'
|
||||
s.version = '6.10.0'
|
||||
|
||||
s.license = { :type => 'MIT', :file => 'LICENSE' }
|
||||
s.summary = 'A toolkit for SQLite databases, with a focus on application development.'
|
||||
|
||||
@@ -374,6 +374,7 @@
|
||||
56E9FACB221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FACA221046FD00C703A8 /* SQLInterpolation+QueryInterface.swift */; };
|
||||
56E9FADA221053DD00C703A8 /* SQL.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56E9FAD7221053DC00C703A8 /* SQL.swift */; };
|
||||
56EA63C5209C7CE3009715B8 /* DerivableRequestTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56EA63C4209C7CE3009715B8 /* DerivableRequestTests.swift */; };
|
||||
56F0383B28C21814000DEBFB /* Database+Cache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0383A28C21814000DEBFB /* Database+Cache.swift */; };
|
||||
56F34FBA24B094B6007513FC /* SQLExpressionIsConstantTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */; };
|
||||
56F34FC224B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */; };
|
||||
56F3E7491E66F83A00BF0F01 /* ResultCodeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F3E7481E66F83A00BF0F01 /* ResultCodeTests.swift */; };
|
||||
@@ -512,6 +513,7 @@
|
||||
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>"; };
|
||||
@@ -776,6 +778,7 @@
|
||||
56EA869D1C932597002BB4DF /* DatabasePoolReadOnlyTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePoolReadOnlyTests.swift; sourceTree = "<group>"; };
|
||||
56EB0AB11BCD787300A3DC55 /* DataMemoryTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DataMemoryTests.swift; sourceTree = "<group>"; };
|
||||
56ED8A7E1DAB8D6800BD0ABC /* FTS5WrapperTokenizerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS5WrapperTokenizerTests.swift; sourceTree = "<group>"; };
|
||||
56F0383A28C21814000DEBFB /* Database+Cache.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Database+Cache.swift"; sourceTree = "<group>"; };
|
||||
56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FoundationNSDateTests.swift; sourceTree = "<group>"; };
|
||||
56F34FB924B094B6007513FC /* SQLExpressionIsConstantTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLExpressionIsConstantTests.swift; sourceTree = "<group>"; };
|
||||
56F34FC124B0A0B7007513FC /* SQLIdentifyingColumnsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SQLIdentifyingColumnsTests.swift; sourceTree = "<group>"; };
|
||||
@@ -1112,6 +1115,13 @@
|
||||
path = GRDBCombineTests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
564390D42414FC2C00BA61E6 /* Frameworks */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
);
|
||||
name = Frameworks;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
5653EABF20944B1300F46237 /* Association */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -1436,6 +1446,7 @@
|
||||
56A238701B9C75030082EB20 /* Configuration.swift */,
|
||||
56DAA2DA1DE9C827006E10C8 /* Cursor.swift */,
|
||||
56A238711B9C75030082EB20 /* Database.swift */,
|
||||
56F0383A28C21814000DEBFB /* Database+Cache.swift */,
|
||||
566B91221FA4CF810012D5B0 /* Database+Schema.swift */,
|
||||
566B91081FA4C3960012D5B0 /* Database+Statements.swift */,
|
||||
4E13D2F22769B87F0037588C /* DatabaseBackupProgress.swift */,
|
||||
@@ -1580,6 +1591,8 @@
|
||||
DC37742D19C8CC90004FCF85 /* GRDB */,
|
||||
DC10500F19C904DD00D8CA30 /* Tests */,
|
||||
DC3773F419C8CBB3004FCF85 /* Products */,
|
||||
564390D42414FC2C00BA61E6 /* Frameworks */,
|
||||
5643676D272EDF2400C718C7 /* Scripts */,
|
||||
);
|
||||
indentWidth = 4;
|
||||
sourceTree = "<group>";
|
||||
@@ -2013,6 +2026,7 @@
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
568ECA9F25D7E53E00B71526 /* SQLOrdering.swift in Sources */,
|
||||
56F0383B28C21814000DEBFB /* Database+Cache.swift in Sources */,
|
||||
56713FDD2691F409006153C3 /* JSONRequiredEncoder.swift in Sources */,
|
||||
56158780288D875E00A67323 /* Optional.swift in Sources */,
|
||||
563EF42D2161180D007DAACD /* AssociationAggregate.swift in Sources */,
|
||||
|
||||
@@ -182,7 +182,7 @@ public struct Configuration {
|
||||
/// var config = Configuration()
|
||||
/// config.transactionClock = .custom { db in /* return some Date */ }
|
||||
/// ```
|
||||
public var transactionClock: any TransactionClock = .default
|
||||
public var transactionClock: TransactionClock = .default
|
||||
|
||||
// MARK: - Managing SQLite Connections
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
extension Database {
|
||||
func withCache<T>(atPath path: String, execute: () throws -> T) throws -> T {
|
||||
GRDBPrecondition(attachedCache == nil, "Database is already cached.")
|
||||
|
||||
return try throwingFirstError {
|
||||
attachedCache = AttachedCache(
|
||||
schema: .attached("cache"),
|
||||
statementCache: StatementCache(database: self))
|
||||
try self.execute(literal: "ATTACH DATABASE \(path) AS cache")
|
||||
return try execute()
|
||||
} finally: {
|
||||
attachedCache = nil
|
||||
try self.execute(sql: "DETACH DATABASE cache")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Statement {
|
||||
/// Returns a statement ready for iterating the results of this statement
|
||||
/// with a DatabaseCursor.
|
||||
///
|
||||
/// The result is not the same statement as the receiver if we cache the
|
||||
/// statement's results.
|
||||
func databaseCursorStatement(with arguments: StatementArguments?) throws -> Statement {
|
||||
// Should we cache statement results and return a new statement on the cached values?
|
||||
guard
|
||||
// Don't cache until we were instructed to.
|
||||
let attachedCache = database.attachedCache,
|
||||
|
||||
// Only cache read-only statements.
|
||||
isReadonly,
|
||||
|
||||
// Only cache statements that access user tables.
|
||||
databaseRegion
|
||||
.filteringTables({ !Database.isSQLiteInternalTable($0) && !Database.isGRDBInternalTable($0) })
|
||||
.isEmpty == false,
|
||||
|
||||
// Only cache statements that can build a name for the cache table.
|
||||
let cacheTableName,
|
||||
|
||||
// Only cache statements for which we can guarantee rowid ordering
|
||||
// without ambiguity.
|
||||
case let statementColumns = columnNames.map({ $0.lowercased() }),
|
||||
let rowid = ["rowid", "_rowid_", "oid"].first(where: { !statementColumns.contains($0) })
|
||||
else {
|
||||
// Don't cache: return self.
|
||||
// Reset before cursor iteration: the statement may be reused.
|
||||
try prepareExecution(withArguments: arguments)
|
||||
return self
|
||||
}
|
||||
|
||||
// Cache the results if not done yet
|
||||
let cacheTable = Database.TableIdentifier(schemaID: attachedCache.schema, name: cacheTableName)
|
||||
try database.execute(sql: """
|
||||
CREATE TABLE IF NOT EXISTS \(cacheTable.quotedDatabaseIdentifier) AS \(sql)
|
||||
""", arguments: arguments ?? self.arguments)
|
||||
|
||||
// Return a statement on the cached values, preserving the order of the
|
||||
// original rows.
|
||||
//
|
||||
// Quoting <https://sqlite.org/lang_createtable.html#create_table_as_select_statements>:
|
||||
//
|
||||
// > Tables created using CREATE TABLE AS are initially populated with
|
||||
// > the rows of data returned by the SELECT statement. Rows are
|
||||
// > assigned contiguously ascending rowid values, starting with 1, in
|
||||
// > the order that they are returned by the SELECT statement.
|
||||
let statement = try attachedCache.statementCache.statement("""
|
||||
SELECT * FROM \(cacheTable.quotedDatabaseIdentifier) ORDER BY \(rowid)
|
||||
""")
|
||||
// Reset before cursor iteration: the statement may be reused.
|
||||
try statement.reset()
|
||||
return statement
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,10 @@ extension Database {
|
||||
case let .attached(name): return "\(name).sqlite_master"
|
||||
}
|
||||
}
|
||||
|
||||
func table(_ name: String) -> TableIdentifier {
|
||||
TableIdentifier(schemaID: self, name: name)
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier of a database table or view.
|
||||
@@ -210,7 +214,7 @@ extension Database {
|
||||
}
|
||||
}
|
||||
|
||||
private func tableExists(_ table: TableIdentifier) throws -> Bool {
|
||||
func tableExists(_ table: TableIdentifier) throws -> Bool {
|
||||
try exists(type: .table, name: table.name, in: table.schemaID)
|
||||
}
|
||||
|
||||
|
||||
@@ -331,6 +331,20 @@ public final class Database: CustomStringConvertible, CustomDebugStringConvertib
|
||||
}
|
||||
}
|
||||
|
||||
class AttachedCache {
|
||||
var schema: SchemaIdentifier
|
||||
var statementCache: StatementCache
|
||||
|
||||
init(schema: Database.SchemaIdentifier, statementCache: StatementCache) {
|
||||
self.schema = schema
|
||||
self.statementCache = statementCache
|
||||
}
|
||||
}
|
||||
/// [**Experimental**](http://github.com/groue/GRDB.swift#what-are-experimental-features)
|
||||
///
|
||||
/// The attached database that caches the results of requests.
|
||||
var attachedCache: AttachedCache?
|
||||
|
||||
// MARK: - Private properties
|
||||
|
||||
/// Support for ``Configuration/busyMode``.
|
||||
|
||||
@@ -225,22 +225,21 @@ extension DatabaseQueue: DatabaseReader {
|
||||
|
||||
public func asyncRead(_ value: @escaping (Result<Database, Error>) -> Void) {
|
||||
writer.async { db in
|
||||
defer {
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
do {
|
||||
// Enter read-only mode before starting a transaction, so that the
|
||||
// transaction commit does not trigger database observation.
|
||||
// See <https://github.com/groue/GRDB.swift/pull/1213>.
|
||||
try db.beginReadOnly()
|
||||
// The transaction guarantees snapshot isolation against eventual
|
||||
// external connection.
|
||||
try db.beginTransaction(.deferred)
|
||||
value(.success(db))
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
return
|
||||
}
|
||||
|
||||
value(.success(db))
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,23 +273,20 @@ extension DatabaseQueue: DatabaseReader {
|
||||
writer.execute { db in
|
||||
// ... and that no transaction is opened.
|
||||
GRDBPrecondition(!db.isInsideTransaction, "must not be called from inside a transaction.")
|
||||
|
||||
defer {
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.commit()
|
||||
try? db.endReadOnly()
|
||||
}
|
||||
|
||||
do {
|
||||
// Enter read-only mode before starting a transaction, so that the
|
||||
// transaction commit does not trigger database observation.
|
||||
// See <https://github.com/groue/GRDB.swift/pull/1213>.
|
||||
try db.beginReadOnly()
|
||||
try db.beginTransaction(.deferred)
|
||||
value(.success(db))
|
||||
try db.beginReadOnly()
|
||||
} catch {
|
||||
value(.failure(error))
|
||||
return
|
||||
}
|
||||
|
||||
value(.success(db))
|
||||
|
||||
// Ignore error because we can not notify it.
|
||||
try? db.endReadOnly()
|
||||
try? db.commit()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -168,9 +168,14 @@ public struct DatabaseRegion {
|
||||
// TransactionObserver protocol. By removing internal SQLite tables from
|
||||
// the observed region, we optimize database observation.
|
||||
//
|
||||
// We also remove GRDB internal tables (cache tables).
|
||||
//
|
||||
// And by canonicalizing table names, we remove views, and help the
|
||||
// `isModified` methods.
|
||||
try ignoringInternalSQLiteTables().canonicalTables(db)
|
||||
let notInternalTables = filteringTables {
|
||||
!Database.isSQLiteInternalTable($0) && !Database.isGRDBInternalTable($0)
|
||||
}
|
||||
return try notInternalTables.canonicalTables(db)
|
||||
}
|
||||
|
||||
/// Returns a region only made of actual tables with their canonical names.
|
||||
@@ -190,11 +195,11 @@ public struct DatabaseRegion {
|
||||
return region
|
||||
}
|
||||
|
||||
/// Returns a region which doesn't contain any SQLite internal table.
|
||||
private func ignoringInternalSQLiteTables() -> DatabaseRegion {
|
||||
/// Returns a region which only contains the filtered tables
|
||||
func filteringTables(_ predicate: (String) -> Bool) -> DatabaseRegion {
|
||||
guard let tableRegions else { return .fullDatabase }
|
||||
let filteredRegions = tableRegions.filter {
|
||||
!Database.isSQLiteInternalTable($0.key.rawValue)
|
||||
predicate($0.key.rawValue)
|
||||
}
|
||||
return DatabaseRegion(tableRegions: filteredRegions)
|
||||
}
|
||||
|
||||
@@ -342,6 +342,25 @@ extension DatabaseValue: CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension DatabaseValue {
|
||||
/// A string that represented the value in a lossless and
|
||||
/// unambiguous way.
|
||||
var losslessDescription: String {
|
||||
switch storage {
|
||||
case .null:
|
||||
return "NULL"
|
||||
case let .string(string):
|
||||
return String(reflecting: string)
|
||||
case let .double(double):
|
||||
return double.description
|
||||
case let .int64(int64):
|
||||
return int64.description
|
||||
case let .blob(data):
|
||||
return "X'" + data.map { String(format: "%02X", $0) }.joined() + "'"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares DatabaseValue like SQLite.
|
||||
///
|
||||
/// See RxGRDB for tests.
|
||||
|
||||
@@ -147,6 +147,7 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
private let columnIndex: CInt
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
let statement = try statement.databaseCursorStatement(with: arguments)
|
||||
self._statement = statement
|
||||
if let adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
@@ -154,9 +155,6 @@ public final class DatabaseValueCursor<Value: DatabaseValueConvertible>: Databas
|
||||
} else {
|
||||
columnIndex = 0
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.prepareExecution(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -289,13 +289,14 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// ```
|
||||
///
|
||||
/// - note: Usage of this method is discouraged, because waiting on the
|
||||
/// returned ``DatabaseFuture`` blocks a thread. You may prefer
|
||||
/// ``spawnConcurrentRead(_:)`` instead.
|
||||
/// returned ``DatabaseFuture`` blocks a thread. You may prefer the
|
||||
/// asynchronous version of this method: ``spawnConcurrentRead(_:)``.
|
||||
/// - parameter value: A closure which accesses the database.
|
||||
func concurrentRead<T>(_ value: @escaping (Database) throws -> T) -> DatabaseFuture<T>
|
||||
|
||||
// Exposed for RxGRDB and GRBCombine. Naming is not stabilized.
|
||||
/// Schedules read-only database operations for execution.
|
||||
/// Schedules read-only database operations for execution, and
|
||||
/// returns immediately.
|
||||
///
|
||||
/// - note: [**🔥 EXPERIMENTAL**](https://github.com/groue/GRDB.swift/blob/master/README.md#what-are-experimental-features)
|
||||
///
|
||||
@@ -310,7 +311,7 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// by the database writer.
|
||||
///
|
||||
/// In the example below, the number of players is fetched concurrently with
|
||||
/// the player insertion. Yet it is guaranteed to return zero:
|
||||
/// the player insertion. Yet the future is guaranteed to return zero:
|
||||
///
|
||||
/// ```swift
|
||||
/// try writer.writeWithoutTransaction { db in
|
||||
@@ -333,10 +334,6 @@ public protocol DatabaseWriter: DatabaseReader {
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// - important: The database operations are executed immediately,
|
||||
/// or asynchronously, depending on the actual class
|
||||
/// of `DatabaseWriter`.
|
||||
///
|
||||
/// - parameter value: A closure which accesses the database. Its argument
|
||||
/// is a `Result` that provides the database connection, or the failure
|
||||
/// that would prevent establishing the read access to the database.
|
||||
|
||||
+1
-3
@@ -1360,11 +1360,9 @@ public final class RowCursor: DatabaseCursor {
|
||||
@usableFromInline let _row: Row // Reused for performance
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
let statement = try statement.databaseCursorStatement(with: arguments)
|
||||
self._statement = statement
|
||||
self._row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.prepareExecution(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -572,7 +572,7 @@ public struct ScopeAdapter: RowAdapter {
|
||||
///
|
||||
/// - parameter scopes: A dictionary that maps scope names to
|
||||
/// row adapters.
|
||||
public init(_ scopes: [String: any RowAdapter]) {
|
||||
public init(_ scopes: [String: RowAdapter]) {
|
||||
// Use SuffixRowAdapter(fromIndex: 0) as the identity adapter
|
||||
self.init(base: SuffixRowAdapter(fromIndex: 0), scopes: scopes)
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import CryptoKit
|
||||
import Foundation
|
||||
|
||||
/// A raw SQLite statement, suitable for the SQLite C API.
|
||||
@@ -95,6 +96,23 @@ public final class Statement {
|
||||
authorizerEventKinds.contains(where: \.isDelete)
|
||||
}
|
||||
|
||||
/// A string that represented the statement in a lossless and
|
||||
/// unambiguous way.
|
||||
lazy var losslessDescription: String = {
|
||||
"\(sql); -- \(arguments.losslessDescription)"
|
||||
}()
|
||||
|
||||
/// A table name for caching the results of this statement
|
||||
lazy var cacheTableName: String? = {
|
||||
guard #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.0, *),
|
||||
let losslessDescription = losslessDescription.data(using: .utf8)
|
||||
else {
|
||||
return nil
|
||||
}
|
||||
let digest = Insecure.SHA1.hash(data: losslessDescription)
|
||||
return "grdb_cache_" + digest.map { String(format: "%02X", $0) }.joined()
|
||||
}()
|
||||
|
||||
@usableFromInline
|
||||
unowned let database: Database
|
||||
|
||||
@@ -779,10 +797,7 @@ final class StatementCursor: DatabaseCursor {
|
||||
|
||||
// Use Statement.makeCursor() instead
|
||||
init(statement: Statement, arguments: StatementArguments? = nil) throws {
|
||||
self._statement = statement
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.prepareExecution(withArguments: arguments)
|
||||
_statement = try statement.databaseCursorStatement(with: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -1030,7 +1045,7 @@ public struct StatementArguments: Hashable {
|
||||
/// The result is nil unless all array elements conform to the
|
||||
/// ``DatabaseValueConvertible`` protocol.
|
||||
public init?(_ array: [Any]) {
|
||||
var values = [(any DatabaseValueConvertible)?]()
|
||||
var values = [DatabaseValueConvertible?]()
|
||||
for value in array {
|
||||
guard let dbValue = DatabaseValue(value: value) else {
|
||||
return nil
|
||||
@@ -1389,4 +1404,19 @@ extension StatementArguments: CustomStringConvertible {
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments {
|
||||
/// A string that represented the value in a lossless and
|
||||
/// unambiguous way.
|
||||
var losslessDescription: String {
|
||||
var chunks: [String] = []
|
||||
for value in values {
|
||||
chunks.append(value.losslessDescription)
|
||||
}
|
||||
for (key, value) in namedValues.sorted(by: { $0.key < $1.key }) {
|
||||
chunks.append("\(key): \(value.losslessDescription)")
|
||||
}
|
||||
return chunks.joined(separator: ",")
|
||||
}
|
||||
}
|
||||
|
||||
extension StatementArguments: Sendable { }
|
||||
@@ -214,6 +214,7 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
@usableFromInline let columnIndex: CInt
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
let statement = try statement.databaseCursorStatement(with: arguments)
|
||||
self._statement = statement
|
||||
if let adapter {
|
||||
// adapter may redefine the index of the leftmost column
|
||||
@@ -221,9 +222,6 @@ where Value: DatabaseValueConvertible & StatementColumnConvertible
|
||||
} else {
|
||||
columnIndex = 0
|
||||
}
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.prepareExecution(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -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? any DatabaseValueConvertible.Type {
|
||||
if let type = T.self as? DatabaseValueConvertible.Type {
|
||||
// Prefer DatabaseValueConvertible decoding over Decodable.
|
||||
// This allows custom database decoding, such as decoding Date from
|
||||
// String, for example.
|
||||
|
||||
@@ -454,7 +454,7 @@ class DatabaseObservationBroker {
|
||||
|
||||
if savepointStack.isEmpty {
|
||||
// Notify now
|
||||
for statementObservation in statementObservations where statementObservation.tracksEvent(event) {
|
||||
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
|
||||
statementObservation.transactionObservation.databaseWillChange(with: event)
|
||||
}
|
||||
} else {
|
||||
@@ -479,7 +479,7 @@ class DatabaseObservationBroker {
|
||||
|
||||
if savepointStack.isEmpty {
|
||||
// Notify now
|
||||
for statementObservation in statementObservations where statementObservation.tracksEvent(event) {
|
||||
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
|
||||
statementObservation.transactionObservation.databaseDidChange(with: event)
|
||||
}
|
||||
} else {
|
||||
@@ -639,7 +639,7 @@ class DatabaseObservationBroker {
|
||||
|
||||
for (event, statementObservations) in eventsBuffer {
|
||||
assert(statementObservations.isEmpty || !database.isReadOnly, "Read-only transactions are not notified")
|
||||
for statementObservation in statementObservations where statementObservation.tracksEvent(event) {
|
||||
for statementObservation in statementObservations where statementObservation.predicate.evaluate(event) {
|
||||
event.send(to: statementObservation.transactionObservation)
|
||||
}
|
||||
}
|
||||
@@ -969,18 +969,12 @@ final class TransactionObservation {
|
||||
struct StatementObservation {
|
||||
var transactionObservation: TransactionObservation
|
||||
|
||||
/// A predicate that filters database events that should be notified.
|
||||
///
|
||||
/// Call this predicate as a method:
|
||||
///
|
||||
/// ```
|
||||
/// if observation.tracksEvent(event) { ... }
|
||||
/// ```
|
||||
var tracksEvent: DatabaseEventPredicate
|
||||
/// Filters database events that should be notified.
|
||||
var predicate: DatabaseEventPredicate
|
||||
|
||||
init(transactionObservation: TransactionObservation, trackingEvents predicate: DatabaseEventPredicate) {
|
||||
self.transactionObservation = transactionObservation
|
||||
self.tracksEvent = predicate
|
||||
self.predicate = predicate
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1453,7 +1447,7 @@ enum DatabaseEventPredicate {
|
||||
/// statement authorizer.
|
||||
case matching(observedEventKinds: [DatabaseEventKind], authorizerEventKinds: [DatabaseEventKind])
|
||||
|
||||
func callAsFunction(_ event: some DatabaseEventProtocol) -> Bool {
|
||||
func evaluate(_ event: some DatabaseEventProtocol) -> Bool {
|
||||
switch self {
|
||||
case .all:
|
||||
return true
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
/// An instance of WALSnapshot records the state of a WAL mode database for some
|
||||
/// specific point in history.
|
||||
///
|
||||
@@ -22,6 +20,13 @@
|
||||
///
|
||||
/// See <https://www.sqlite.org/c3ref/snapshot.html>.
|
||||
final class WALSnapshot: Sendable {
|
||||
// Xcode 14 (Swift 5.7) ships with a macOS SDK that misses snapshot support.
|
||||
// Xcode 14.1 (Swift 5.7.1) ships with a macOS SDK that has snapshot support.
|
||||
// This is the meaning of (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst)))
|
||||
// swiftlint:disable:next line_length
|
||||
#if SQLITE_ENABLE_SNAPSHOT || (!GRDBCUSTOMSQLITE && !GRDBCIPHER && (compiler(>=5.7.1) || !(os(macOS) || targetEnvironment(macCatalyst))))
|
||||
static let available = true
|
||||
|
||||
let sqliteSnapshot: UnsafeMutablePointer<sqlite3_snapshot>
|
||||
|
||||
init(_ db: Database) throws {
|
||||
@@ -62,5 +67,15 @@ final class WALSnapshot: Sendable {
|
||||
func compare(_ other: WALSnapshot) -> CInt {
|
||||
sqlite3_snapshot_cmp(sqliteSnapshot, other.sqliteSnapshot)
|
||||
}
|
||||
}
|
||||
#else
|
||||
static let available = false
|
||||
|
||||
init(_ db: Database) throws {
|
||||
throw DatabaseError(resultCode: .SQLITE_MISUSE, message: "snapshots are not available")
|
||||
}
|
||||
|
||||
func compare(_ other: WALSnapshot) -> CInt {
|
||||
preconditionFailure("snapshots are not available")
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -27,13 +27,12 @@ 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
|
||||
|
||||
|
||||
@@ -1,581 +0,0 @@
|
||||
# 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
-3
@@ -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: any DatabaseWriter,
|
||||
_ writer: DatabaseWriter,
|
||||
completion: @escaping (Database, Error?) -> Void)
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
@@ -167,5 +167,3 @@ extension ValueObservation {
|
||||
where Reducer == ValueReducers.Fetch<Value>
|
||||
{ preconditionFailure() }
|
||||
}
|
||||
|
||||
// swiftlint:enable all
|
||||
@@ -612,12 +612,7 @@ extension SQLRelation {
|
||||
guard !isDistinct else {
|
||||
return try fetchTrivialCount(db)
|
||||
}
|
||||
|
||||
// <https://github.com/groue/GRDB.swift/issues/1357>
|
||||
guard selection.allSatisfy(\.isTriviallyCountable) else {
|
||||
return try fetchTrivialCount(db)
|
||||
}
|
||||
|
||||
|
||||
// SELECT expr1, expr2, ... FROM tableName ...
|
||||
// ->
|
||||
// SELECT COUNT(*) FROM tableName ...
|
||||
|
||||
@@ -244,18 +244,6 @@ extension SQLSelection {
|
||||
return .literal(sqlLiteral.qualified(with: alias))
|
||||
}
|
||||
}
|
||||
|
||||
/// Supports SQLRelation.fetchCount.
|
||||
///
|
||||
/// See <https://github.com/groue/GRDB.swift/issues/1357>
|
||||
var isTriviallyCountable: Bool {
|
||||
switch impl {
|
||||
case .aliasedExpression, .literal:
|
||||
return false
|
||||
case .allColumns, .qualifiedAllColumns, .expression:
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension [SQLSelection] {
|
||||
|
||||
@@ -2,6 +2,7 @@ extension Database {
|
||||
|
||||
// MARK: - Database Schema
|
||||
|
||||
// TODO: deprecate just before GRDB 6
|
||||
/// Creates a database table.
|
||||
///
|
||||
/// For example:
|
||||
@@ -320,6 +321,7 @@ extension Database {
|
||||
try execute(sql: "DROP TABLE \(name.quotedDatabaseIdentifier)")
|
||||
}
|
||||
|
||||
// TODO: deprecate just before GRDB 6
|
||||
/// Creates an index.
|
||||
///
|
||||
/// For example:
|
||||
|
||||
@@ -803,11 +803,9 @@ public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor {
|
||||
let _row: Row // Instantiated once, reused for performance
|
||||
|
||||
init(statement: Statement, arguments: StatementArguments? = nil, adapter: (any RowAdapter)? = nil) throws {
|
||||
let statement = try statement.databaseCursorStatement(with: arguments)
|
||||
self._statement = statement
|
||||
_row = try Row(statement: statement).adapted(with: adapter, layout: statement)
|
||||
|
||||
// Assume cursor is created for immediate iteration: reset and set arguments
|
||||
try statement.prepareExecution(withArguments: arguments)
|
||||
}
|
||||
|
||||
deinit {
|
||||
|
||||
@@ -522,6 +522,7 @@
|
||||
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>"; };
|
||||
@@ -1583,6 +1584,7 @@
|
||||
DC37742D19C8CC90004FCF85 /* GRDB */,
|
||||
F3BA7FED1CFB21F8003DC1BA /* GRDBCustomSQLite */,
|
||||
DC10500F19C904DD00D8CA30 /* Tests */,
|
||||
5643676E272EDF3700C718C7 /* Scripts */,
|
||||
DC3773F419C8CBB3004FCF85 /* Products */,
|
||||
);
|
||||
indentWidth = 4;
|
||||
|
||||
@@ -52,13 +52,10 @@ MAX_IOS_DESTINATION := $(shell xcrun simctl list -j devices available | Scripts/
|
||||
MIN_TVOS_DESTINATION := $(shell xcrun simctl list -j devices available | Scripts/destination.rb | grep tvOS | sort -n | head -1 | cut -wf 3 | sed 's/\(.*\)/"platform=tvOS Simulator,id=\1"/')
|
||||
MAX_TVOS_DESTINATION := $(shell xcrun simctl list -j devices available | Scripts/destination.rb | grep tvOS | sort -rn | head -1 | cut -wf 3 | sed 's/\(.*\)/"platform=tvOS Simulator,id=\1"/')
|
||||
|
||||
# If xcbeautify or xcpretty is available, use it for xcodebuild output
|
||||
# If xcpretty is available, use it for xcodebuild output
|
||||
XCPRETTY =
|
||||
XCBEAUTIFY_PATH := $(shell command -v xcbeautify 2> /dev/null)
|
||||
XCPRETTY_PATH := $(shell command -v xcpretty 2> /dev/null)
|
||||
ifdef XCBEAUTIFY_PATH
|
||||
XCPRETTY = | xcbeautify
|
||||
else ifdef XCPRETTY_PATH
|
||||
ifdef XCPRETTY_PATH
|
||||
XCPRETTY = | xcpretty -c
|
||||
endif
|
||||
|
||||
@@ -131,7 +128,6 @@ test_framework_GRDBCustomSQLiteOSX: SQLiteCustom
|
||||
$(XCODEBUILD) \
|
||||
-project GRDBCustom.xcodeproj \
|
||||
-scheme GRDBCustom \
|
||||
-destination "platform=macOS" \
|
||||
$(TEST_ACTIONS) \
|
||||
$(XCPRETTY)
|
||||
|
||||
@@ -253,7 +249,6 @@ test_install_SPM_Project:
|
||||
$(XCODEBUILD) \
|
||||
-project Tests/SPM/PlainProject/Plain.xcodeproj \
|
||||
-scheme Plain \
|
||||
-destination "platform=macOS" \
|
||||
-configuration Release \
|
||||
clean build \
|
||||
$(XCPRETTY)
|
||||
@@ -271,7 +266,6 @@ test_install_SPM_macos_release:
|
||||
$(XCODEBUILD) \
|
||||
-project Tests/SPM/macos/macos.xcodeproj \
|
||||
-scheme macos \
|
||||
-destination "platform=macOS" \
|
||||
-configuration Release \
|
||||
clean build \
|
||||
$(XCPRETTY)
|
||||
@@ -289,7 +283,6 @@ test_install_customSQLite: SQLiteCustom
|
||||
$(XCODEBUILD) \
|
||||
-project Tests/CustomSQLite/CustomSQLite.xcodeproj \
|
||||
-scheme CustomSQLite \
|
||||
-destination "platform=macOS" \
|
||||
-configuration Release \
|
||||
clean build \
|
||||
$(XCPRETTY)
|
||||
@@ -364,7 +357,6 @@ test_performance:
|
||||
$(XCODEBUILD) \
|
||||
-project Tests/Performance/GRDBPerformance/GRDBPerformance.xcodeproj \
|
||||
-scheme GRDBOSXPerformanceComparisonTests \
|
||||
-destination "platform=macOS" \
|
||||
build-for-testing test-without-building
|
||||
|
||||
# Target that setups SQLite custom builds with extra compilation options.
|
||||
|
||||
@@ -10,9 +10,6 @@ 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" {
|
||||
|
||||
@@ -11,13 +11,13 @@
|
||||
|
||||
---
|
||||
|
||||
**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)
|
||||
**Latest release**: March 20, 2023 • [version 6.10.0](https://github.com/groue/GRDB.swift/tree/v6.10.0) • [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+ • SQLite 3.19.3+ • Swift 5.7+ / Xcode 14+
|
||||
|
||||
| Swift version | GRDB version |
|
||||
| -------------- | ----------------------------------------------------------- |
|
||||
| **Swift 5.7+** | **v6.10.2** |
|
||||
| **Swift 5.7+** | **v6.10.0** |
|
||||
| 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: [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices)
|
||||
- :bulb: [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md)
|
||||
- :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 [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) Guide.
|
||||
> :bulb: **Tip**: after you have read this chapter, check the [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) 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 [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices) for further information.
|
||||
See the [query interface](#the-query-interface) and [Good Practices for Designing Record Types](Documentation/GoodPracticesForDesigningRecordTypes.md) for further information.
|
||||
|
||||
|
||||
## Record Class
|
||||
|
||||
@@ -62,6 +62,7 @@ opt_in_rules:
|
||||
- sorted_first_last
|
||||
- sorted_imports
|
||||
- toggle_bool
|
||||
- unused_capture_list
|
||||
- vertical_parameter_alignment_on_call
|
||||
- yoda_condition
|
||||
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>FMWK</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>6.10.2</string>
|
||||
<string>6.10.0</string>
|
||||
<key>CFBundleSignature</key>
|
||||
<string>????</string>
|
||||
<key>CFBundleVersion</key>
|
||||
|
||||
@@ -395,7 +395,7 @@ class DatabaseWriterWritePublisherTests : XCTestCase {
|
||||
return writer
|
||||
}
|
||||
|
||||
func test(writer: some DatabaseWriter, iteration: Int) throws {
|
||||
func test(writer: 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: [any SQLSelectable] = [Column("name")]
|
||||
static let databaseSelection: [SQLSelectable] = [Column("name")]
|
||||
}
|
||||
|
||||
private struct ExtendedB : TableRecord {
|
||||
static let databaseTableName = "b"
|
||||
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
static let databaseSelection: [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: [any SQLSelectable] = [Column("name")]
|
||||
static let databaseSelection: [SQLSelectable] = [Column("name")]
|
||||
}
|
||||
|
||||
private struct ExtendedB : TableRecord {
|
||||
static let databaseTableName = "b"
|
||||
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
static let databaseSelection: [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: [any SQLSelectable] = [Column("name")]
|
||||
static let databaseSelection: [SQLSelectable] = [Column("name")]
|
||||
}
|
||||
|
||||
private struct ExtendedC : TableRecord {
|
||||
static let databaseTableName = "c"
|
||||
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
}
|
||||
|
||||
/// Test SQL generation
|
||||
|
||||
@@ -20,7 +20,7 @@ class ColumnExpressionTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
// Test databaseSelection
|
||||
static let databaseSelection: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score]
|
||||
static let databaseSelection: [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: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score]
|
||||
static let databaseSelection: [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: [any SQLSelectable] = [Columns.id, Columns.name, Columns.score]
|
||||
static let databaseSelection: [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: [any SQLSelectable] = [CodingKeys.id, CodingKeys.name, CodingKeys.score]
|
||||
static let databaseSelection: [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 -> (any DatabaseValueConvertible)? { preconditionFailure() }
|
||||
func finalize() throws -> DatabaseValueConvertible? { preconditionFailure() }
|
||||
}
|
||||
|
||||
private class UserDatabaseAggregate2 : DatabaseAggregate {
|
||||
required init() { }
|
||||
func step(_ dbValues: [DatabaseValue]) throws { }
|
||||
func finalize() throws -> (any DatabaseValueConvertible)? { preconditionFailure() }
|
||||
func finalize() throws -> 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: any FTS5Tokenizer { preconditionFailure() }
|
||||
var wrappedTokenizer: 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: some DatabaseReader) throws {
|
||||
func test(_ dbReader: 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: some DatabaseReader) throws {
|
||||
func test(_ dbReader: DatabaseReader) throws {
|
||||
let semaphore1 = DispatchSemaphore(value: 0)
|
||||
let semaphore2 = DispatchSemaphore(value: 0)
|
||||
|
||||
@@ -316,7 +316,7 @@ class DatabaseAbortedTransactionTests : GRDBTestCase {
|
||||
}
|
||||
return dbWriter
|
||||
}
|
||||
func test(_ dbReader: some DatabaseReader) throws {
|
||||
func test(_ dbReader: DatabaseReader) throws {
|
||||
do {
|
||||
try dbReader.unsafeRead { db in
|
||||
try db.inTransaction {
|
||||
|
||||
@@ -18,7 +18,7 @@ class DatabaseAggregateTests: GRDBTestCase {
|
||||
func testAggregateReturningNull() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ values: [DatabaseValue]) { }
|
||||
func finalize() -> (any DatabaseValueConvertible)? { nil }
|
||||
func finalize() -> 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() -> (any DatabaseValueConvertible)? { Int64(1) }
|
||||
func finalize() -> 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() -> (any DatabaseValueConvertible)? { 1e100 }
|
||||
func finalize() -> 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() -> (any DatabaseValueConvertible)? { "foo" }
|
||||
func finalize() -> 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() -> (any DatabaseValueConvertible)? {
|
||||
func finalize() -> DatabaseValueConvertible? {
|
||||
"foo".data(using: .utf8)
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ class DatabaseAggregateTests: GRDBTestCase {
|
||||
func testAggregateReturningCustomValueType() throws {
|
||||
struct Aggregate : DatabaseAggregate {
|
||||
func step(_ values: [DatabaseValue]) { }
|
||||
func finalize() -> (any DatabaseValueConvertible)? { CustomValueType() }
|
||||
func finalize() -> 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: (any DatabaseValueConvertible)?
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = dbValues[0].isNull
|
||||
}
|
||||
func finalize() -> (any DatabaseValueConvertible)? { result }
|
||||
func finalize() -> 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: (any DatabaseValueConvertible)?
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = Int64.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
func finalize() -> (any DatabaseValueConvertible)? { result }
|
||||
func finalize() -> 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: (any DatabaseValueConvertible)?
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = Double.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
func finalize() -> (any DatabaseValueConvertible)? { result }
|
||||
func finalize() -> 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: (any DatabaseValueConvertible)?
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = String.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
func finalize() -> (any DatabaseValueConvertible)? { result }
|
||||
func finalize() -> 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: (any DatabaseValueConvertible)?
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = Data.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
func finalize() -> (any DatabaseValueConvertible)? { result }
|
||||
func finalize() -> 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: (any DatabaseValueConvertible)?
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = CustomValueType.fromDatabaseValue(dbValues[0])
|
||||
}
|
||||
func finalize() -> (any DatabaseValueConvertible)? { result }
|
||||
func finalize() -> 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() -> (any DatabaseValueConvertible)? { "foo" }
|
||||
func finalize() -> 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: (any DatabaseValueConvertible)?
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = String.fromDatabaseValue(dbValues[0])?.uppercased()
|
||||
}
|
||||
func finalize() -> (any DatabaseValueConvertible)? { result }
|
||||
func finalize() -> 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: (any DatabaseValueConvertible)?
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
let ints = dbValues.compactMap { Int.fromDatabaseValue($0) }
|
||||
result = ints.reduce(0, +)
|
||||
}
|
||||
func finalize() -> (any DatabaseValueConvertible)? { result }
|
||||
func finalize() -> 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: (any DatabaseValueConvertible)?
|
||||
var result: DatabaseValueConvertible?
|
||||
mutating func step(_ dbValues: [DatabaseValue]) {
|
||||
result = dbValues.count
|
||||
}
|
||||
func finalize() -> (any DatabaseValueConvertible)? { result }
|
||||
func finalize() -> 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() -> (any DatabaseValueConvertible)? { fatalError() }
|
||||
func finalize() -> 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() -> (any DatabaseValueConvertible)? { fatalError() }
|
||||
func finalize() -> 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() -> (any DatabaseValueConvertible)? { fatalError() }
|
||||
func finalize() -> 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() -> (any DatabaseValueConvertible)? { fatalError() }
|
||||
func finalize() -> 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 -> (any DatabaseValueConvertible)? {
|
||||
func finalize() throws -> 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 -> (any DatabaseValueConvertible)? {
|
||||
func finalize() throws -> 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 -> (any DatabaseValueConvertible)? {
|
||||
func finalize() throws -> 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 -> (any DatabaseValueConvertible)? {
|
||||
func finalize() throws -> 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 -> (any DatabaseValueConvertible)? { sum }
|
||||
func finalize() throws -> 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 -> (any DatabaseValueConvertible)? { sum }
|
||||
func finalize() throws -> 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() -> (any DatabaseValueConvertible)? { nil }
|
||||
func finalize() -> 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() -> (any DatabaseValueConvertible)? { fatalError() }
|
||||
func finalize() -> 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 -> (any DatabaseValueConvertible)? {
|
||||
func finalize() throws -> DatabaseValueConvertible? {
|
||||
throw DatabaseError(message: "boo")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ class DatabaseDateDecodingStrategyTests: GRDBTestCase {
|
||||
_ db: Database,
|
||||
record: T.Type,
|
||||
date: (T) -> Date?,
|
||||
databaseValue: (any DatabaseValueConvertible)?,
|
||||
databaseValue: DatabaseValueConvertible?,
|
||||
with test: (Date?) -> Void) throws
|
||||
{
|
||||
let request = SQLRequest<Void>(sql: "SELECT ? AS date", arguments: [databaseValue])
|
||||
@@ -79,13 +79,7 @@ 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: some DatabaseValueConvertible,
|
||||
_ test: (Date) -> Void)
|
||||
throws
|
||||
{
|
||||
private func test<Strategy: StrategyProvider>(_ db: Database, strategy: Strategy.Type, databaseValue: 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,12 +87,7 @@ class DatabaseDateEncodingStrategyTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
private func test<Strategy: StrategyProvider>(
|
||||
strategy: Strategy.Type,
|
||||
encodesDate date: Date,
|
||||
as value: some DatabaseValueConvertible)
|
||||
throws
|
||||
{
|
||||
private func test<Strategy: StrategyProvider>(strategy: Strategy.Type, encodesDate date: Date, as value: DatabaseValueConvertible) throws {
|
||||
try test(record: RecordWithDate<Strategy>(date: date), expectedStorage: value.databaseValue.storage)
|
||||
try test(record: RecordWithOptionalDate<Strategy>(date: date), expectedStorage: value.databaseValue.storage)
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ class DatabaseReaderTests : GRDBTestCase {
|
||||
}
|
||||
return dbWriter
|
||||
}
|
||||
func test(_ dbReader: some DatabaseReader) throws {
|
||||
func test(_ dbReader: 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: some DatabaseReader) async throws {
|
||||
func test(_ dbReader: 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: some DatabaseReader) throws {
|
||||
func test(_ dbReader: 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: some DatabaseReader) async throws {
|
||||
func test(_ dbReader: 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: some DatabaseReader) throws {
|
||||
func test(_ dbReader: 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: some DatabaseReader) async throws {
|
||||
func test(_ dbReader: 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: some DatabaseReader) throws {
|
||||
func test(_ dbReader: 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: some DatabaseReader) throws {
|
||||
func test(_ dbReader: 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: some DatabaseWriter) throws {
|
||||
func test(_ dbWriter: 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: some DatabaseReader) throws {
|
||||
func test(_ dbReader: 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: some DatabaseReader) throws {
|
||||
func test(_ dbReader: 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: some DatabaseReader) throws {
|
||||
func test(_ dbReader: 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: some DatabaseReader) throws {
|
||||
func test(_ dbReader: 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: some DatabaseReader) throws {
|
||||
func test(_ source: DatabaseReader) throws {
|
||||
let dest = try makeDatabaseQueue(configuration: Configuration())
|
||||
try source.backup(to: dest)
|
||||
let count = try dest.read { db in
|
||||
|
||||
@@ -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: some DatabaseReader) throws -> [String] {
|
||||
func fetchAllItemNames(_ dbReader: DatabaseReader) throws -> [String] {
|
||||
try dbReader.read { db in
|
||||
try String.fetchAll(db, sql: "SELECT * FROM items ORDER BY name")
|
||||
}
|
||||
|
||||
@@ -622,4 +622,66 @@ class DatabaseTests : GRDBTestCase {
|
||||
// 999 should be safe: https://www.sqlite.org/limits.html
|
||||
XCTAssertGreaterThanOrEqual(count, 999)
|
||||
}
|
||||
|
||||
func testCache() throws {
|
||||
// See "In-memory Databases And Shared Cache" in https://www.sqlite.org/inmemorydb.html
|
||||
dbConfiguration.prepareDatabase { db in
|
||||
db.trace { print($0)}
|
||||
}
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.writeWithoutTransaction { db in // transaction prevents DETACH DATABASE from wording
|
||||
var region = DatabaseRegion()
|
||||
try db.recordingSelection(®ion) {
|
||||
try db.withCache(atPath: ":memory:") {
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE player(id INTEGER PRIMARY KEY, name TEXT);
|
||||
CREATE TABLE award(id INTEGER PRIMARY KEY, playerId INTEGER REFERENCES player(id), color TEXT);
|
||||
INSERT INTO player (name) VALUES ('Barbara');
|
||||
INSERT INTO player (name) VALUES ('Zoe');
|
||||
INSERT INTO player (name) VALUES ('Gaston');
|
||||
INSERT INTO player (name) VALUES ('Bernard');
|
||||
INSERT INTO player (name) VALUES ('Henri');
|
||||
INSERT INTO award(playerId, color) VALUES (1, 'Gold');
|
||||
INSERT INTO award(playerId, color) VALUES (1, 'Silver');
|
||||
INSERT INTO award(playerId, color) VALUES (1, 'Gold');
|
||||
INSERT INTO award(playerId, color) VALUES (2, 'Silver');
|
||||
INSERT INTO award(playerId, color) VALUES (3, 'Gold');
|
||||
INSERT INTO award(playerId, color) VALUES (4, 'Silver');
|
||||
""")
|
||||
|
||||
struct Player: TableRecord, FetchableRecord, Decodable {
|
||||
static let awards = hasMany(Award.self)
|
||||
var id: Int64
|
||||
var name: String
|
||||
}
|
||||
struct Award: TableRecord, FetchableRecord, Decodable {
|
||||
var id: Int64
|
||||
var playerId: Int64
|
||||
var color: String
|
||||
}
|
||||
|
||||
do {
|
||||
_ = try Row.fetchAll(db, sql: "SELECT * FROM player ORDER BY name")
|
||||
}
|
||||
do {
|
||||
// Test cache ordering with rowid disambiguation
|
||||
_ = try Row.fetchAll(db, sql: "SELECT rowid AS rowID, * FROM player ORDER BY name")
|
||||
}
|
||||
do {
|
||||
struct PlayerWithAwards: FetchableRecord, Decodable {
|
||||
var player: Player
|
||||
var awards: [Award]
|
||||
}
|
||||
|
||||
_ = try Player
|
||||
.filter(Column("name") != "Gaston")
|
||||
.including(all: Player.awards.filter(Column("color") != "Gold"))
|
||||
.asRequest(of: PlayerWithAwards.self)
|
||||
.fetchAll(db)
|
||||
}
|
||||
}
|
||||
}
|
||||
try print(region.observableRegion(db))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,11 +53,7 @@ class DatabaseUUIDEncodingStrategyTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
private func test<Strategy: StrategyProvider>(
|
||||
strategy: Strategy.Type,
|
||||
encodesUUID uuid: UUID,
|
||||
as value: any DatabaseValueConvertible)
|
||||
throws {
|
||||
private func test<Strategy: StrategyProvider>(strategy: Strategy.Type, encodesUUID uuid: UUID, as value: DatabaseValueConvertible) throws {
|
||||
try test(record: RecordWithUUID<Strategy>(uuid: uuid), expectedStorage: value.databaseValue.storage)
|
||||
try test(record: RecordWithOptionalUUID<Strategy>(uuid: uuid), expectedStorage: value.databaseValue.storage)
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ extension Book : FetchableRecord {
|
||||
|
||||
extension Book : MutablePersistableRecord {
|
||||
static let databaseTableName = "books"
|
||||
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
|
||||
func encode(to container: inout PersistenceContainer) {
|
||||
container[.rowID] = id
|
||||
|
||||
@@ -19,7 +19,7 @@ extension Book : FetchableRecord {
|
||||
|
||||
extension Book : MutablePersistableRecord {
|
||||
static let databaseTableName = "books"
|
||||
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
static let databaseSelection: [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: any FTS5Tokenizer
|
||||
let wrappedTokenizer: 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: any FTS5Tokenizer
|
||||
let wrappedTokenizer: 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: any FTS5Tokenizer
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
let synonyms: [Set<String>]
|
||||
|
||||
init(db: Database, arguments: [String]) throws {
|
||||
|
||||
@@ -20,7 +20,7 @@ extension Book : FetchableRecord {
|
||||
|
||||
extension Book : MutablePersistableRecord {
|
||||
static let databaseTableName = "books"
|
||||
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
static let databaseSelection: [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: any FTS5Tokenizer
|
||||
var wrappedTokenizer: 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: any FTS5Tokenizer
|
||||
let wrappedTokenizer: 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: any FTS5Tokenizer
|
||||
let wrappedTokenizer: 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: any FTS5Tokenizer
|
||||
let wrappedTokenizer: FTS5Tokenizer
|
||||
|
||||
required init(db: Database, arguments: [String]) throws {
|
||||
wrappedTokenizer = try db.makeTokenizer(.unicode61(diacritics: .removeLegacy, separators: ["X"]))
|
||||
|
||||
@@ -2,7 +2,7 @@ import XCTest
|
||||
import GRDB
|
||||
|
||||
class FoundationNSUUIDTests: GRDBTestCase {
|
||||
private func assert(_ value: (any DatabaseValueConvertible)?, isDecodedAs expectedUUID: NSUUID?) throws {
|
||||
private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: NSUUID?) throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
if let expectedUUID {
|
||||
let decodedUUID = try NSUUID.fetchOne(db, sql: "SELECT ?", arguments: [value])
|
||||
|
||||
@@ -3,7 +3,7 @@ import Foundation
|
||||
import GRDB
|
||||
|
||||
class FoundationUUIDTests: GRDBTestCase {
|
||||
private func assert(_ value: (any DatabaseValueConvertible)?, isDecodedAs expectedUUID: UUID?) throws {
|
||||
private func assert(_ value: DatabaseValueConvertible?, isDecodedAs expectedUUID: UUID?) throws {
|
||||
try makeDatabaseQueue().read { db in
|
||||
if let expectedUUID {
|
||||
let decodedUUID = try UUID.fetchOne(db, sql: "SELECT ?", arguments: [value])
|
||||
|
||||
@@ -147,37 +147,19 @@ class GRDBTestCase: XCTestCase {
|
||||
}
|
||||
|
||||
// Compare SQL strings (ignoring leading and trailing white space and semicolons.
|
||||
func assertEqualSQL(
|
||||
_ db: Database,
|
||||
_ request: some FetchRequest,
|
||||
_ sql: String,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
throws
|
||||
{
|
||||
func assertEqualSQL<Request: FetchRequest>(_ db: Database, _ request: Request, _ 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(
|
||||
_ databaseReader: some DatabaseReader,
|
||||
_ request: some FetchRequest,
|
||||
_ sql: String,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
throws
|
||||
{
|
||||
func assertEqualSQL<Request: FetchRequest>(_ databaseReader: DatabaseReader, _ request: Request, _ 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(
|
||||
_ databaseReader: some DatabaseReader,
|
||||
_ request: some FetchRequest)
|
||||
-> String
|
||||
{
|
||||
func sql<Request: FetchRequest>(_ databaseReader: DatabaseReader, _ request: Request) -> String {
|
||||
try! databaseReader.unsafeRead { db in
|
||||
try request.makeStatement(db).makeCursor().next()
|
||||
return lastSQLQuery!
|
||||
|
||||
@@ -50,7 +50,7 @@ private struct T2: Codable, FetchableRecord, TableRecord {
|
||||
|
||||
private struct T3: Codable, FetchableRecord, TableRecord {
|
||||
static let databaseTableName = "t3"
|
||||
static let databaseSelection: [any SQLSelectable] = [Column("t1id"), Column("name")]
|
||||
static let databaseSelection: [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 [any SQLExpressible]).contains(Col.name.collating(.nocase)))),
|
||||
sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [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 [any SQLExpressible]).contains(Col.name).collating(.nocase))),
|
||||
sql(dbQueue, tableRequest.filter((["arthur", "barbara"] as [SQLExpressible]).contains(Col.name).collating(.nocase))),
|
||||
"SELECT * FROM \"readers\" WHERE (\"name\" COLLATE NOCASE) IN ('arthur', 'barbara')")
|
||||
|
||||
// Sequence.contains(): IN operator
|
||||
|
||||
@@ -136,21 +136,6 @@ class QueryInterfaceRequestTests: GRDBTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for <https://github.com/groue/GRDB.swift/issues/1357>
|
||||
func testIssue1357() throws {
|
||||
let dbQueue = try makeDatabaseQueue()
|
||||
try dbQueue.inDatabase { db in
|
||||
let request = tableRequest
|
||||
.annotated(with: Column("name").forKey("alt"))
|
||||
.filter(Column("alt").detached)
|
||||
|
||||
XCTAssertEqual(try request.fetchCount(db), 0)
|
||||
XCTAssertEqual(lastSQLQuery, """
|
||||
SELECT COUNT(*) FROM (SELECT *, "name" AS "alt" FROM "readers" WHERE "alt")
|
||||
""")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Select
|
||||
|
||||
|
||||
@@ -14,14 +14,14 @@ class RecordPersistenceConflictPolicyTests: GRDBTestCase {
|
||||
|
||||
func testDefaultPersistenceConflictPolicy() {
|
||||
let record = RecordWithoutPersistenceConflictPolicy()
|
||||
let policy = type(of: record).persistenceConflictPolicy
|
||||
let policy = type(of: record as MutablePersistableRecord).persistenceConflictPolicy
|
||||
XCTAssertEqual(policy.conflictResolutionForInsert, .abort)
|
||||
XCTAssertEqual(policy.conflictResolutionForUpdate, .abort)
|
||||
}
|
||||
|
||||
func testConfigurablePersistenceConflictPolicy() {
|
||||
let record = RecordWithPersistenceConflictPolicy()
|
||||
let policy = type(of: record).persistenceConflictPolicy
|
||||
let policy = type(of: record as MutablePersistableRecord).persistenceConflictPolicy
|
||||
XCTAssertEqual(policy.conflictResolutionForInsert, .fail)
|
||||
XCTAssertEqual(policy.conflictResolutionForUpdate, .ignore)
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ private class Person : Record, Hashable {
|
||||
|
||||
// Record
|
||||
|
||||
override static var databaseSelection: [any SQLSelectable] {
|
||||
override static var databaseSelection: [SQLSelectable] {
|
||||
[AllColumns(), Column.rowID]
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ class RowFromDictionaryTests : RowTestCase {
|
||||
}
|
||||
|
||||
func testRowValueAtIndex() {
|
||||
let dictionary: [String: (any DatabaseValueConvertible)?] = ["a": 0, "b": 1, "c": 2]
|
||||
let dictionary: [String: 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: (any DatabaseValueConvertible)?] = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)]
|
||||
let dictionary: [String: 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: (any DatabaseValueConvertible)?] = ["null": nil, "int64": 1, "double": 1.1, "string": "foo", "blob": "SQLite".data(using: .utf8)]
|
||||
let dictionary: [String: 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 }
|
||||
|
||||
@@ -220,7 +220,7 @@ extension SQLLiteralTests {
|
||||
do {
|
||||
// Existential
|
||||
let query: SQL = """
|
||||
SELECT \(AllColumns() as any SQLSelectable)
|
||||
SELECT \(AllColumns() as SQLSelectable)
|
||||
FROM player
|
||||
"""
|
||||
|
||||
@@ -234,7 +234,7 @@ extension SQLLiteralTests {
|
||||
do {
|
||||
// Existential
|
||||
let query: SQL = """
|
||||
SELECT \(nil as (any SQLSelectable)?)
|
||||
SELECT \(nil as SQLSelectable?)
|
||||
"""
|
||||
|
||||
let (sql, arguments) = try query.build(db)
|
||||
@@ -293,7 +293,7 @@ extension SQLLiteralTests {
|
||||
do {
|
||||
// Existential
|
||||
let query: SQL = """
|
||||
INSERT INTO \(tableOf: Player() as any TableRecord) DEFAULT VALUES
|
||||
INSERT INTO \(tableOf: Player() as 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: [any SQLSelectable] = [Column("id"), Column("name")]
|
||||
static let databaseSelection: [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: [any SQLExpressible] = [Column("a"), Column("b") + 2]
|
||||
let expressions: [SQLExpressible] = [Column("a"), Column("b") + 2]
|
||||
let query: SQL = """
|
||||
SELECT * FROM player
|
||||
WHERE teamId IN \(set)
|
||||
@@ -742,21 +742,8 @@ extension SQLLiteralTests {
|
||||
|
||||
do {
|
||||
// Here we test that users can define functions that return
|
||||
// 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 {
|
||||
// literal expressions.
|
||||
func date(_ value: SQLExpressible) -> SQLExpression {
|
||||
SQL("DATE(\(value))").sqlExpression
|
||||
}
|
||||
let createdAt = Column("createdAt")
|
||||
@@ -769,22 +756,8 @@ extension SQLLiteralTests {
|
||||
do {
|
||||
// Here we test that users can still define functions that
|
||||
// return literal expressions with the previously
|
||||
// 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 {
|
||||
// supported technique.
|
||||
func date(_ value: SQLExpressible) -> SQLExpression {
|
||||
SQL("DATE(\(value.sqlExpression))").sqlExpression
|
||||
}
|
||||
let createdAt = Column("createdAt")
|
||||
@@ -827,15 +800,10 @@ extension SQLLiteralTests {
|
||||
|
||||
func testProtocolResolution() throws {
|
||||
// SQL can feed ordering, selection, and expressions.
|
||||
acceptOrderingTerm_generic(SQL(""))
|
||||
acceptSelectable_generic(SQL(""))
|
||||
acceptSpecificExpressible_generic(SQL(""))
|
||||
acceptExpressible_generic(SQL(""))
|
||||
|
||||
acceptOrderingTerm_existential(SQL(""))
|
||||
acceptSelectable_existential(SQL(""))
|
||||
acceptSpecificExpressible_existential(SQL(""))
|
||||
acceptExpressible_existential(SQL(""))
|
||||
acceptOrderingTerm(SQL(""))
|
||||
acceptSelectable(SQL(""))
|
||||
acceptSpecificExpressible(SQL(""))
|
||||
acceptExpressible(SQL(""))
|
||||
|
||||
// SQL can build complex expressions and orderings
|
||||
_ = SQL("") + 1
|
||||
@@ -844,24 +812,18 @@ extension SQLLiteralTests {
|
||||
// Swift String literals are interpreted as String, even when SQL
|
||||
// is an accepted type.
|
||||
//
|
||||
// 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))
|
||||
|
||||
// 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))
|
||||
|
||||
// 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_generic(""), "a")
|
||||
XCTAssertEqual(overloaded_generic(SQL("")), "SQLSpecificExpressible")
|
||||
// should not compile: XCTAssertEqual(overloaded_existential(""), "a")
|
||||
XCTAssertEqual(overloaded_existential(SQL("")), "SQLSpecificExpressible")
|
||||
|
||||
// should not compile: XCTAssertEqual(overloaded(""), "a")
|
||||
XCTAssertEqual(overloaded(SQL("")), "SQLSpecificExpressible")
|
||||
|
||||
// In practice:
|
||||
try makeDatabaseQueue().write { db in
|
||||
struct Player: TableRecord { }
|
||||
@@ -888,65 +850,33 @@ extension SQLLiteralTests {
|
||||
|
||||
// Support for testProtocolResolution()
|
||||
@discardableResult
|
||||
private func acceptOrderingTerm_generic(_ x: some SQLOrderingTerm) -> String {
|
||||
private func acceptOrderingTerm(_ x: SQLOrderingTerm) -> String {
|
||||
String(describing: type(of: x))
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
private func acceptSelectable_generic(_ x: some SQLSelectable) -> String {
|
||||
private func acceptSelectable(_ x: SQLSelectable) -> String {
|
||||
String(describing: type(of: x))
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
private func acceptSpecificExpressible_generic(_ x: some SQLSpecificExpressible) -> String {
|
||||
private func acceptSpecificExpressible(_ x: SQLSpecificExpressible) -> String {
|
||||
String(describing: type(of: x))
|
||||
}
|
||||
|
||||
@discardableResult
|
||||
private func acceptExpressible_generic(_ x: some SQLExpressible) -> String {
|
||||
private func acceptExpressible(_ x: SQLExpressible) -> String {
|
||||
String(describing: type(of: x))
|
||||
}
|
||||
|
||||
private func overloaded_generic(_ x: some SQLOrderingTerm) -> String {
|
||||
private func overloaded(_ x: SQLOrderingTerm) -> String {
|
||||
"SQLOrderingTerm"
|
||||
}
|
||||
|
||||
private func overloaded_generic(_ x: some SQLSelectable) -> String {
|
||||
private func overloaded(_ x: SQLSelectable) -> String {
|
||||
"SQLSelectable"
|
||||
}
|
||||
|
||||
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 {
|
||||
private func overloaded(_ x: SQLSpecificExpressible & SQLSelectable & SQLOrderingTerm) -> String {
|
||||
"SQLSpecificExpressible"
|
||||
}
|
||||
@@ -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: (any DatabaseValueConvertible)?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]]
|
||||
let ageDicts: [[String: 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: (any DatabaseValueConvertible)?]] = [["age": 20], ["age": 30], ["age": 40], ["age": 50]]
|
||||
let ageDicts: [[String: 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 [(any DatabaseValueConvertible)?])
|
||||
let arguments = StatementArguments([name, age] as [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 [(any DatabaseValueConvertible)?])
|
||||
let arguments = StatementArguments([name, age] as [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 [(any DatabaseValueConvertible)?])
|
||||
let arguments = StatementArguments([name, age] as [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: (any DatabaseValueConvertible)?])
|
||||
let arguments = StatementArguments(["name": name, "age": age] as [String: 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: (any DatabaseValueConvertible)?])
|
||||
let arguments = StatementArguments(["name": name, "age": age] as [String: 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: (any DatabaseValueConvertible)?])
|
||||
let arguments = StatementArguments(["name": name, "age": age] as [String: 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: (any DatabaseValueConvertible)?])
|
||||
let arguments = StatementArguments(["name": name, "age": age] as [String: 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: (any DatabaseValueConvertible)?])
|
||||
let arguments = StatementArguments(["name": name, "age": age] as [String: 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: (any DatabaseValueConvertible)?])
|
||||
let arguments = StatementArguments(["name": name, "age": age] as [String: DatabaseValueConvertible?])
|
||||
|
||||
let updateStatement = try db.makeStatement(sql: "INSERT INTO persons (firstName, lastName, age) VALUES (:name, :name, :age)")
|
||||
updateStatement.setUncheckedArguments(arguments)
|
||||
|
||||
@@ -103,7 +103,7 @@ class TableRecordTests: GRDBTestCase {
|
||||
func testExtendedDatabaseSelection() throws {
|
||||
struct Record: TableRecord {
|
||||
static let databaseTableName = "t1"
|
||||
static let databaseSelection: [any SQLSelectable] = [AllColumns(), Column.rowID]
|
||||
static let databaseSelection: [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: [any SQLSelectable] = [Column("a"), Column("b")]
|
||||
static let databaseSelection: [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: some DatabaseWriter) throws {
|
||||
private func setupArtistDatabase(in dbWriter: DatabaseWriter) throws {
|
||||
try dbWriter.write { db in
|
||||
try db.execute(sql: """
|
||||
CREATE TABLE artists (
|
||||
|
||||
@@ -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: [[(any DatabaseValueConvertible)?]] = [
|
||||
let persons: [[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: [[(any DatabaseValueConvertible)?]] = [
|
||||
let persons: [[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: (any DatabaseValueConvertible)?]] = [
|
||||
let persons: [[String: 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: (any DatabaseValueConvertible)?]] = [
|
||||
let persons: [[String: 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: some DatabaseReader) throws -> String {
|
||||
private func region(sql: String, in dbReader: DatabaseReader) throws -> String {
|
||||
try dbReader.read { db in
|
||||
try db
|
||||
.makeStatement(sql: sql)
|
||||
@@ -436,17 +436,13 @@ class ValueObservationPrintTests: GRDBTestCase {
|
||||
onChange: { _ in expectation.fulfill() })
|
||||
withExtendedLifetime(cancellable) {
|
||||
waitForExpectations(timeout: 1, handler: 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(), [
|
||||
XCTAssertEqual(logger.strings, [
|
||||
"start",
|
||||
"fetch",
|
||||
"value: nil",
|
||||
"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, any DatabaseWriter) throws -> Void,
|
||||
fails testFailure: (Failure, DatabaseWriter) throws -> Void,
|
||||
setup: (Database) throws -> Void,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line)
|
||||
|
||||
@@ -542,7 +542,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
}
|
||||
|
||||
// Start observation and deallocate cancellable after second change
|
||||
var cancellable: (any DatabaseCancellable)?
|
||||
var cancellable: 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: (any DatabaseCancellable)!
|
||||
var cancellable: 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: (any DatabaseCancellable)? = nil
|
||||
var cancellable: 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: (any DatabaseCancellable)? = nil
|
||||
var cancellable: DatabaseCancellable? = nil
|
||||
_ = cancellable // Avoid "Variable 'cancellable' was written to, but never read" warning
|
||||
var shouldStopObservation = false
|
||||
let observation = ValueObservation(
|
||||
@@ -782,11 +782,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
assertValueObservationRecordingMatch(recorded: counts, expected: [0, 1, 2])
|
||||
|
||||
// Observation was ended
|
||||
#if compiler(>=5.8)
|
||||
await fulfillment(of: [cancellationExpectation], timeout: 2)
|
||||
#else
|
||||
wait(for: [cancellationExpectation], timeout: 2)
|
||||
#endif
|
||||
}
|
||||
|
||||
try await AsyncTest(test).run { try DatabaseQueue() }
|
||||
@@ -820,11 +816,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
assertValueObservationRecordingMatch(recorded: counts, expected: [0, 1, 2])
|
||||
|
||||
// Observation was ended
|
||||
#if compiler(>=5.8)
|
||||
await fulfillment(of: [cancellationExpectation], timeout: 2)
|
||||
#else
|
||||
wait(for: [cancellationExpectation], timeout: 2)
|
||||
#endif
|
||||
}
|
||||
|
||||
try await AsyncTest(test).run { try DatabaseQueue() }
|
||||
@@ -862,11 +854,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
assertValueObservationRecordingMatch(recorded: counts, expected: [0, 1, 2])
|
||||
|
||||
// Observation was ended
|
||||
#if compiler(>=5.8)
|
||||
await fulfillment(of: [cancellationExpectation], timeout: 2)
|
||||
#else
|
||||
wait(for: [cancellationExpectation], timeout: 2)
|
||||
#endif
|
||||
}
|
||||
|
||||
try await AsyncTest(test).run { try DatabaseQueue() }
|
||||
@@ -901,11 +889,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
assertValueObservationRecordingMatch(recorded: counts, expected: [0])
|
||||
|
||||
// Observation was ended
|
||||
#if compiler(>=5.8)
|
||||
await fulfillment(of: [cancellationExpectation], timeout: 2)
|
||||
#else
|
||||
wait(for: [cancellationExpectation], timeout: 2)
|
||||
#endif
|
||||
}
|
||||
|
||||
try await AsyncTest(test).run { try DatabaseQueue() }
|
||||
@@ -952,11 +936,7 @@ class ValueObservationTests: GRDBTestCase {
|
||||
XCTAssertEqual(cancelledValue, "cancelled loop")
|
||||
|
||||
// Make sure observation was cancelled as well
|
||||
#if compiler(>=5.8)
|
||||
await fulfillment(of: [cancellationExpectation], timeout: 2)
|
||||
#else
|
||||
wait(for: [cancellationExpectation], timeout: 2)
|
||||
#endif
|
||||
}
|
||||
|
||||
try await AsyncTest(test).run { try DatabaseQueue() }
|
||||
|
||||
@@ -29,7 +29,7 @@ private struct Item: Codable, FetchableRecord, PersistableRecord {
|
||||
i9 = row[9]
|
||||
}
|
||||
|
||||
static let databaseSelection: [any SQLSelectable] = [
|
||||
static let databaseSelection: [SQLSelectable] = [
|
||||
Column("i0"),
|
||||
Column("i1"),
|
||||
Column("i2"),
|
||||
|
||||
Reference in new issue
Block a user