beginReadOnly() runs `PRAGMA query_only = 1` before it increases
readOnlyDepth. When a cancelled task interrupts the PRAGMA after it has
enabled query_only, the PRAGMA throws, the depth is not increased, and
endReadOnly() never runs. The connection then stays read-only, and every
later write fails with SQLITE_READONLY.
Run the PRAGMA with ignoringInterruption, as endReadOnly() already does
since #1839.
Fixes#1899
sqlite_compileoption_used('USE_URI') reports whether the option is
defined, not its value, and is missing when compile-option diagnostics
are omitted. Check the error from the open instead: without URI
filenames, the path is in a missing "file:" directory and fails with
SQLITE_CANTOPEN.
This commit is inspired by #1873 from @guidedways, who detected an unexpectedly quadratic behavior in the way we build database regions from the statement authorizer
The issue with `observesAllDatabaseChanges` is that this was a misleading name: transaction observers are not notified of changes that are performed in a save point that is eventually rollbacked.
By exposing the DatabaseEventObservationStrategy type, we allow for a future extra flag that ignores save points, trading observation precision for a reduced memory footprint.
- Adds Database+SQLCipher extension with SQLCipher operations, enabled by #if SQLITE_HAS_CODEC
- Adjusts Import Statements to import SQLCipher when SQLCipher trait is enabled (or SQLCipher swiftSetting is set)
I did not know statement compilation could fail when database is interrupted until #1838. A ROLLBACK statement would not even compile due to the FTS5 statement leak reported in https://sqlite.org/forum/forumpost/137c7662b389fa18
This pull request fixes#1826, which broke `make test_GRDBDemo` with Xcode 26.0.1.
To reproduce the failure:
- Remove from ~/Library/Developer/Xcode/DerivedData all previous builds of GRDB and related stuff
- Run `make distclean test_GRDBDemo`
We expect a success, but it fails with error "Unable to find module dependency: 'GRDBSQLite'".
GRDBCIPHER is now just a marker for importing SQLCipher with CocoaPods.
Also, enable all APIs that used to be disabled with SQLCipher, and skip tests that require a specific SQLite version.
We can not use `#if Trait` because Xcode does not enable those compiler flags. Always count on Apple for delivering the best quality software.
So now we import the default SPM SQLite last, after all other cases have been excluded.
The GRDB framework (GRDB.xcodeproj and GRDB via CocoaPods) is distinct from the default SPM trait, so we detect it with GRDBFRAMEWORK.
When GRDB eventually adds methods to the DatabaseSchemaSource protocol, our chained schema source will implement chaining on those new methods.
When users write their own custom chaining schema source, the compiler will not tell them that they have to chain the new methods when they upgrade GRDB. The built-in (and correct) implementation of chaining helps avoiding this scenario.
Database.changesCount calls sqlite3_changes(), whose documentation says:
> https://sqlite.org/c3ref/changes.html
> Changes to a view that are intercepted by INSTEAD OF triggers are not counted.
Since we want to support INSTEAD OF triggers well, so that record types can be based on views, we switch to sqlite3_total_changes().
This method is necessary for the customization of schema introspection: it must be possible to fallback on the primitive SQLite schema introspection when needed.
This allows us to apply the encoding strategies for Data, Date, UUID when we know we need it, i.e. when we know the primary key, and this happens when we access the database - in a nonisolated fashion.
This is required because the value of databaseSelection is not required to be Sendable. This forces TableRecord.relationForAll to postpone the definition of the selection until we access the database - in a nonisolated fashion.
DatabaseAggregate does not support isolated conformances: it must be able to aggregate values whenever a database access is performed. This can happen in a nonisolated fashion.
If we don't have warnings about explicit nil initialization, then we have a warning about the name of a disabled rule which is now deprecated. In all cases, we have a warning.
So let's just write 2025 Swift, ignore that rule, and call it a day.
We now recommend:
enum Columns {
static let id = Column("id")
static let title = Column("title")
static let latitude = Column("latitude")
static let longitude = Column("longitude")
}
Instead of the previous recommendation:
enum Columns: String, ColumnExpression {
case id, title, latitude, longitude
}
This is because SE-0438 does not support Metatype Keypaths for enums. A request like `Place.order(\.title)` does not compile with a String enum.
This reverts 7ffc332327
At the time, selectID was replaced with selectPrimaryKey(as:) because:
> Since Optional is a database value like others, selectID would be a request of optionals for records with an optional ID type:
>
> struct Player: Identifiable, MutablePersistableRecord {
> var id: Int64?
> }
>
> Player.selectID() // QueryInterface<Int64?>
>
> This is not good, because primary keys are not null. And those requests would fetch impractical types such as [Int64?], Set<Int64?>, Int64??.
This problem is reintroduced, but we now recommend against optional ids in https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/recordrecommendedpractices. And record with optional ids can use selectPrimaryKey(as:).
This uses the deprecated `strcmp` interface on Windows, which requires
the C library to be imported. Add the missing import to allow building
on Windows.
This allows the user to call those methods with an Array, or any other collection at hand (including lazy ones)
This change makes `return coalesce(columns.lazy.map { $0.name })` iterate lazily. Before this commit, `map` was returning a non-lazy Array.
ChatGPT remarks:
# Overview Section:
The phrase "GRDB optimally schedules those database access closures, in the best interest of the application" is vague and could benefit from more detail on how the scheduling optimizes for concurrency.
# Concurrency Warnings in Swift 6:
"We will address these issues, and provide general guidance in the following sections." This sentence suggests that detailed solutions will be discussed, but it is unclear how each error is related to the following section titles. A more specific reference to which section will cover what would help orient the reader.
# Non-Sendable Record Types Section:
The FAQ format is useful, but it could overwhelm the reader. Breaking up the FAQ into subsections with more concise answers or reordering it based on common issues could improve readability.
# Shorthand Closure Notation Section:
The explanation of why shorthand notation leads to warnings is somewhat technical. It may be helpful to clarify what "may introduce data races" means in practical terms for less experienced developers.
# Choosing Between Synchronous and Asynchronous Database Access:
The section recommends using asynchronous access but leaves open-ended guidance like "this may slow down other tasks". Adding a more concrete explanation of how to balance performance between synchronous and asynchronous approaches would benefit developers.
# General Clarification on Sendable:
Throughout the document, Sendable is mentioned frequently, but less-experienced developers might not fully understand why it matters. A short section or footnote on what Sendable is and why it’s important in Swift 6 concurrency might help provide context for readers unfamiliar with the concept.
We can not tell the compiler that we can safely return `sending` results, because fetched values are in the same region as the `db` argument, according to SE-0414 (https://github.com/swiftlang/swift-evolution/blob/main/proposals/0414-region-based-isolation.md#rules-for-merging-isolation-regions).
```
class NotSendable { init() { } }
func fetchNotSendable(_ db: Database) -> NotSendable { fatalError() }
func notOK<T>(_ make: (Database) -> sending T) { }
func ok<T>(_ make: () -> sending T) { }
func usage() {
ok { NotSendable() }
// Returning a task-isolated 'NotSendable' value as a 'sending' result
// risks causing data races.
notOK { db in fetchNotSendable(db) }
}
```
Various attempts at modifying all fetching methods so that they have a `sending` return value have failed.
We were frequently turning those sequences into an Array in order to check their emptiness, and generally were not sure we'd iterate a sequence only once.
Also use `some Sequence` and `some Collection` whenever possible.
Those optionals were just an annoyance. Now, nil results are replaced with `RecordError.recordNotFound`. Such an error is only expected with the IGNORE conflict policy.
Been there, done that: when one feeds a SwiftUI view from an async sequence, the view MUST display an initial empty state, until the Swift Concurrency runtime provides the initial value of the sequence. That's why the demo app uses a Combine publisher for feeding views with database value. This commit removes a misleading reference to async sequences.
Fix#1532
Previous fix would not correctly address #1357 when invalid double-quoted identifiers are interpreted as string literals (Configuration.acceptsDoubleQuotedStringLiterals = true, or SQLCipher 3)
SerializedDatabase hides its allowsUnsafeTransactions property, and makes it thread-safe by protecting it inside its serialized dispatch queue.
WALSnapshotTransaction always notifies when the reader connection is no longer used, and reuses the "isInsideTransaction" wording.
Since #1248, ValueObservation on DatabasePool creates a new database connection when it starts. #1256 has revealed that opening a connection can take too much time, which unfortunate consequences: the first value is notified too late, and we block the main thread when the observation is started in the `.immediate` scheduling :-/
In this commit, ValueObservation on DatabasePool just uses one of the available readers, thus avoiding creating a new connection.
When WAL snapshots are available, a long-running read-only transaction is kept opened on this reader, until we can start observing the write transactions, compare database versions, and perform a fetch+notification if and only if the database was modified.
When WAL snapshots are not available (Xcode 14.0 and macOS, or specific SQLCipher or SQLite builds), a double notification of the initial value is always performed, since we can't prove that the database was not changed between the initial fetch and the write access.
Also:
- Redirect the "Custom Value Types" README chapter to DatabaseValueConvertible documentation.
- Document how to support Tagged https://github.com/pointfreeco/swift-tagged
If the user would forget the PrimaryKeyDefinition, the primary was not defined:
try db.create(table: "membership") { t in
// WRONG: pk is unused
t.primaryKey { pk in
t.column("playerId", .integer)
t.column("teamId", .text)
}
}
The fix is to remove the PrimaryKeyDefinition:
try db.create(table: "membership") { t in
t.primaryKey {
t.column("playerId", .integer)
t.column("teamId", .text)
}
}
In the previous implementation, the snapshot pool would use the same reader connections as the database pool. This would create problem with reentrant reads. Let's make things simple, and not share any database connection.
One can create a snapshot from a read-only pool on a non-WAL database, and that's OK. The snaphost still sees an unchanging database content (but other connections can't write).
This helps tools that intend to declare an observed region without directly accessing it. This will be necessary for (future) snapshot-based observations that postpone actual database access.
This helps tools that perform their own asynchronous jobs that depend on database scheduling. By using the same QoS as the database, they won't create priority inversion or similar scheduling misuses.
Tokenizer arguments only need to be quoted ("foo" -> "'foo'") when we generate SQL for a tokenizer. They must not be quoted when we instantiate a tokenizer with the fts5_tokenizer.xCreate function.
This commit fixes tokenizer instantiation by not quoting arguments when we call the fts5_tokenizer.xCreate function.
Before this fix, the FTS5Tokenizer.tokenize(query:) method would return incorrect tokens.
This creates an opportunity for future `request.filter { ... }` apis that look like standard ones. Why not `Player.filter { $0.score > 1000 }` eventually, perhaps with code generation?
While writing SingletonRecordTest.swift, I tried the solution below, in order to turn a failed update into an insert:
func aroundUpdate(_ db: Database, columns: Set<String>, update: () throws -> PersistenceSuccess) throws {
do {
_ = try update()
} catch {
insert(db)
}
}
But this can't work. This `insert(db)` is unable to provide the information we need in `update()`: the result of the eventual RETURNING clause, and the PersistenceSuccess that contains the persisted PersistenceContainer.
So we now detect two misuses: 1) not calling the action method, and 2) not rethrowing the error of the action method.
The regression was probably due to a bad interaction between Implicitly Opened Existentials (SE-0352) and Opaque Parameter Declarations (SE-0341) which GRDB 6 now uses in a lot of places.
Considering the sample code below:
try db.create(table: ...) { t in
t.column(...).check { $0 != Column(...) }
}
- The `check` method accepts a closure that returns `any SQLExpressible` (the same as GRDB 5)
- The `!=` SQL comparison operator is `(some SQLSpecificExpressible, some SQLSpecificExpressible) -> SQLExpression`, when it was `(SQLSpecificExpressible, SQLSpecificExpressible) -> SQLExpression` in GRDB 5
The compiler has started preferring interpreting the != operator as Column's Equatable implementation, instead of the `!=` SQL comparison operator
We force the compiler to use the SQL comparison operator by removing the Equatable conformance from Column. It was introduced in a70b42c, as a support for a feature that has been removed since then.
This is a breaking change, but this also is an improvement. Now `column1 != column2` has a single meaning, and the library is less prone to similar regressions in the future.
A cool upsert feature is to overwrite an existing value in case of conflict, but another cool upsert feature is to NOT overwrite an existing value. This commit makes it possible to create a ColumnAssignement that does nothing.
Since Optional is a database value like others, selectID would be a request of optionals for records with an optional ID type:
struct Player: Identifiable, MutablePersistableRecord {
var id: Int64?
}
Player.selectID() // QueryInterface<Int64?>
This is not good, because primary keys are not null. And those requests would fetch impractical types such as [Int64?], Set<Int64?>, Int64??.
Instead, we introduce selectPrimaryKey(as:), which allows the user to provide the desired type.
Player.selectPrimaryKey(as: Int64.self) // QueryInterface<Int64>
It used to be rethrowing, but it was then unable to deal with closed databases.
The async version is modified accordingly: it accepts a Result<Database, Error>, instead of a raw Database.
DatabaseMigrator.asyncMigrate is impacted as well: it accepts a Result<Database, Error>, instead of a (Database, Error?) tuple.
Make it possible to test SQLITE_ENABLE_FTS5 and SQLITE_ENABLE_PREUPDATE_HOOK with `make test_SPM`.
This is very handy because Xcode 14 beta 3 has difficulties testing GRDBCustom.
Memory management may not be desirable for all
users of GRDB. `DatabasePool.releaseMemory`
creates a barrier which may cause normally fast
readers to block for a long time. If this is not a
desirable tradeoff, the new
`automaticMemoryManagement` flag in
`Configuration` allows you to disable this feature
of GRDB.
This change:
1. Makes all links use HTTPS (there were a few that used insecure HTTP)
2. Corrects a few links, which previously went to the wrong place
It was easy to find HTTP links—a simple search. I wrote a silly script,
to be run in the browser console, to find the rest:
```js
(() => {
for (const a of document.getElementsByTagName("a")) {
if (!/^#\d+$/.test(a.innerText)) {
continue;
}
const id = a.innerText.slice(1);
const expectedPullHref = `https://github.com/groue/GRDB.swift/pull/${id}`;
const expectedIssueHref = `https://github.com/groue/GRDB.swift/issues/${id}`;
if (a.href !== expectedPullHref && a.href !== expectedIssueHref) {
console.error(`"${a.innerText}" has an invalid href, ${a.href}`);
}
}
})();
```
Hope this helps!
This prevents a build error when running tests with Xcode 13.3:
error: Cycle inside GRDBiOS; building could produce unreliable results. This usually can be resolved by moving the target's Headers build phase before Compile Sources.
Otherwise `make test_install_SPM_Dynamic_Project` uses a default destination, which CAN be the current mac, and thus require code signing:
% make test_install_SPM_Dynamic_Project
...
--- xcodebuild: WARNING: Using the first of multiple matching destinations:
{ platform:macOS, arch:arm64, variant:Designed for [iPad,iPhone], ... }
{ platform:iOS, id:dvtdevice-DVTiPhonePlaceholder-iphoneos:placeholder, name:Any iOS Device }
...
❌ error: Signing for "ios-dynamic" requires a development team. Select a development team in the Signing & Capabilities editor. (in target 'ios-dynamic' from project 'ios-dynamic')
** BUILD FAILED **
Otherwise the behavior is undefined since omitting the type may at some point in time cause Xcode to pull it in as dynamic (when they fix their dependency resolution).
This commit addresses https://github.com/groue/GRDB.swift/issues/1094
The position of the `collating` method is now irrelevant in all those cases:
// name COLLATE NOCASE IN ('foo', 'bar')
["foo", "bar"].contains(Column("name")).collating(.nocase)
["foo", "bar"].contains(Column("name").collating(.nocase))
// name BETWEEN 'foo' AND 'bar' COLLATE NOCASE
("foo"..."bar").contains(Column("name")).collating(.nocase)
("foo"..."bar").contains(Column("name").collating(.nocase))
// (name >= 'foo' COLLATE NOCASE) AND (name < 'bar' COLLATE NOCASE)
("foo"..<"bar").contains(Column("name")).collating(.nocase)
("foo"..<"bar").contains(Column("name").collating(.nocase))
New: support for associated tables WITHOUT ROWID with a compound primary key
New: support for associated views
Checking for the existence of associated CTEs is still not implemented (it fails with "table does not exist" error).
I believe this is incorrect: FB9801372 (UIApplication.didReceiveMemoryWarningNotification should not be declared @MainActor)
Meanwhile, just use the string version.
A workaround based on a MainActor-isolated task can't work due to conflict between compiler version and minimum iOS target:
#if compiler(>=5.5) && canImport(_Concurrency)
if #available(...) { // Check for availability of concurrency runtime
Task { @MainActor [weak self] in
NotificationCenter.default.addObserver(..., name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
}
} else {
// IMPOSSIBLE CASE: No access to Task, no access to notification names
}
#else
NotificationCenter.default.addObserver(..., name: UIApplication.didReceiveMemoryWarningNotification, object: nil)
#endif
Previously, ValueObservation could fetch in a non-isolated way. When an external connection would commit changes, we could fetch inconsistent values. Here we make sure ValueObservation always fetch in an isolated way.
For those specific player requests, trackingConstantRegion is _correct_. But readers may blindly copy and paste, and use trackingConstantRegion when they should not.
So the demo apps prefer the unoptimized but always-correct `tracking` method instead.
This adds an option to convert column names from snake case to camel
case, similar to how JSONDecoder works. In fact, the implementation here
is largely based on JSONDecoder's implementation.
Making sure that `databaseEncodingUserInfo` is being applied to `FetchableRecord.databaseJSONDecoder()`
This tries to cover the other half of the changes in PR groue#958
Making sure that databaseDecodingUserInfo is being applied to FetchableRecord.databaseJSONDecoder()
This tries to cover some of the changes in PR groue#958
The difficulty is due to fast decoding of StatementColumnConvertible, and non-copied Data, from raw SQLite statement.
We want it to be inlinable, and possible in nested rows.
Added missing tests for nested rows
Those arrays were introduced so that we can generate nicer sql: `a AND b AND c`, instead of `(a AND b) AND c`.
This flattening is provided by the && operator and `SQLExpression.associativeBinary`, so those arrays are no longer needed.
Bump min iOS and tvOS versions to 11.4 because Big Sur does not support older simulators:
$ xcrun simctl list runtimes
iOS 10.3 (10.3.1 - 14E8301) - com.apple.CoreSimulator.SimRuntime.iOS-10-3 (unavailable, The iOS 10.3 simulator runtime is not supported on hosts after macOS 10.15.99.)
tvOS 10.2 (10.2 - 14W260) - com.apple.CoreSimulator.SimRuntime.tvOS-10-2 (unavailable, The tvOS 10.2 simulator runtime is not supported on hosts after macOS 10.15.99.)
In order to count the selected columns of a CTE, we do not need to have SQLite compile the whole CTE request when we have information about the selected columns.
SQLSource used to be more or less able to deal with subqueries, as in SELECT ... FROM (SELECT ...).
But we had only one use case for it, the "trivial count query": SELECT COUNT(*) FROM (SELECT ...). And many opportunities for fatal errors, because such subqueries were not generally supported.
So we simplify SQLSource, and implement the trivial count query in another way.
sqlite> create table t(a,b);
sqlite> create index i on t(a like '%a', a, b);
sqlite> explain query plan select * from t where a like '%a';
QUERY PLAN
`--SCAN TABLE t
sqlite> explain query plan select * from t where a not like '%a';
QUERY PLAN
`--SCAN TABLE t
sqlite> explain query plan select * from t where (a like '%a') = 1;
QUERY PLAN
`--SEARCH TABLE t USING COVERING INDEX i (<expr>=?)
sqlite> explain query plan select * from t where (a like '%a') = 0;
QUERY PLAN
`--SEARCH TABLE t USING COVERING INDEX i (<expr>=?)
The difficulty is that system <sqlite3.h> does not contain the expected declarations, even when SQLite is compiled with SQLITE_ENABLE_SNAPSHOT :-(
Since snapshots are not exposed in any public API, we don't bother dealing with availability checks. We just add the missing declarations, and rely on the linker in order to spot eventual errors.
This commit is likely to break Linux builds, though.
- Make it possible to log the database label along with the executed SQL
- Make it possible to avoid arguments expansion
- Make it possible to profile statements
Attempt at fixing this GRDBCombine error:
$ swift build
...
'CSQLite' /.../GRDBCombine/.build/checkouts/CSQLite: error: configuration of package 'CSQLite' is invalid; the 'providers' property can only be used with a System Module Package
This helps GRDBCombine defaulting to a default cancellable when database connection has been closed before the ValueObservation publisher has been subscribed to.
- Deprecate setupMemoryManagement(application:)
- UIApplication is not available on watchOS, so instead of checking against `#if canImport(UIKit)` we use `#if os(iOS)`
Signed-off-by: Pakkito <pe@pierlis.com>
SQLite introduced enhancements to the `ALTER TABLE` command in 3.25.0.
iOS 13.0+, macOS 10.15+, tvOS 13.0+, and watchOS 6.0+ have a SQLite
library bundled higher than 3.25.0.
For more information see https://www.sqlite.org/lang_altertable.html
Before setup, the grdb_migrations table doesn't exist, so calling
`appliedMigrations` would throw an error.
To avoid this, if the table to track migrations doesn't exist yet, we can be
sure no migrations have been run, and we retun the empty set.
FIXES https://github.com/groue/GRDB.swift/issues/652
There is no "fast path" any longer. Performance impact should be minimal since most observers call `stopObservingDatabaseChangesUntilNextTransaction` on first impactful change anyway.
- Rewrite the paragraph as an FAQ
- Explicitly mention the error "Wrong number of statement arguments" and give an example causing such issue.
- Improve the wording and add a link to the SQLite documentation
Adds a flag to SQLSelectQuery indicating that it expects a single record (for example when querying by primary or unique key).
Ensures that this example doesn't add an unnecessary LIMIT 1 to the resulting query:
let request = Player.filter(key: 123) // or Player.filter(key: ["email": "me@example.com"])
let player = try dbQueue.read { db in try request.fetchOne(db) }
- Renamed `KDFIternations` to `kdfIterations` to better fit naming conventions
- In case of errors setting values return the sqlite error code and message instead of .SQLITE_MISUSE and a generic message
- Fixed formatting/typos in documentation
By removing views from the observed database region, we allow the "single-table observation optimization" to kick in.
Thank you @foxware00 for revealing this opportunity in #441 :-)
This is the real fix for #424. GRDB used to keep unfinished SQLite statements around. Now cursors properly reset their statement when they are done. We no longer have to clear the statement cache before a backup.
Record.select(..., as: Value.self) is equivalent to Record.select(...).asRequest(of: Value.self).
It somewhat improves the readability of some requests:
Player.select(max(Column("score")), as: Int.self)
JSON decoding: when row doesn't contain any Data, we don't want to expose a JSONDecodingRequiredError error to the user. We switch to a detailed conversion error instead (see #384).
We used to check for a standard DecodingError.typeMismatch error with specific message before switching to JSON decoding.
There was a small risk that such an error would not be generated by GRDB. In this case, we'd erroneously switch to JSON decoding instead of throwing the error.
So let's recognize the specific need for JSON decoding with a specific error instead: JSONDecodingRequiredError.
- rename ValueConversionDebuggingInfo to ValueConversionContext
- allow missing value conversion context (when decoding a raw DatabaseValue)
- rename ColumnCursor to FastDatabaseValueCursor
- rename NullableColumnCursor to FastNullableDatabaseValueCursor
- Enable
- Add -DSQLITE_ENABLE_FTS5 to the CFLAGS for SQLCipher (SQLCipher/src/sqlcipher.xcconfig) (via submodule update)
- Add -D SQLITE_ENABLE_FTS5 to swift flags for GRDBCipher (SQLCipher/GRDBCipher.xcconfig)
- Add -D SQLITE_ENABLE_FTS5 to the GRDBCipher Testing Projects
- Updated message in EncryptionTests - SQLCipher changed the message “file is encrypted or is not a database” back to just “file is not a database” in 3.4.2 - seems like an odd choice on their part but is behaving as expected.
> When I first started using GRDB I didn't know SQL or much at all about databases 😬 So I've always really liked the query API. But these days I really appreciate that you support raw SQL too, because it gives me more control and freedom when I need it. 👍👍👍
> I cannot recommend GRDB enough. It works well with Swift and eliminates whole classes of potential programming errors that can be made with Core Data. Also being able to use raw SQL queries if needed can be extremely useful!
> I tried out GRDB since I saw you mention it a few days ago and absolutely love it. It’s so nice and testing the database logic is so much nicer than CoreData
> I LOVE GRDB and highly recommend it. If you don’t need it now, do keep it in mind for future because it’s great and the documentation and support are top notch.
> I’ve been working on a side project recently that uses SwiftUI (+UIKit for parent controllers and nav), Combine, GRDB, and GRDBCombine for automatic updating based on DB changes. I’m really liking this setup.
> How had I never heard of GRDB before this week? Was I the only one missing out, or is this wonderful database library from @groue news to you all too? https://buff.ly/2X8yHGf #iosdev
> Spent the last few weeks integrating it and it’s amazing! And this release brings a whole load more features—especially excited about eager loading of hasMany relationships.
>
> Quite possibly one of the best documented open source libs I’ve come across as well👌🏼
> It’s a great successor for FMDB with tons of great stuff. Worth a look, we have choose it in our new project even if, actually, I preferred not using some of the ‘ORM’ like features.
> If you looking for a SQLite wrapper in Swift, just take a look the GRDB library! 👇🏼 https://github.com/groue/GRDB.swift Well-maintained and documented! ✊🏼
> I love the way issues are handled in GRDB (SQLite for Swift). Groue is so friendly, and always goes above-and-beyond in helping to solve problems or explore new features for the library. It makes me happy to be a GRDB user.
- [Swiftlint](https://github.com/realm/SwiftLint) (present in the `$PATH` or in `/opt/homebrew/bin/`)
2.**Clone the `development` branch on your machine.**
3.**Run `make SQLiteCustom` in the terminal**, at the root of the repository.
This step is not strictly necessary if you do not plan to work on custom SQLite builds. But it will avoid a lot of warnings in Xcode.
4.**Open `GRDB.xcworkspace`.** This workspace contains six projects:
-`GRDB.xcodeproj`: the project which contains the GRDB framework and test targets. The sources are organized in two groups:
-`GRDB`: GRDB sources
-`Tests`: GRDB tests
-`GRDBCustom.xcodeproj`: the project which builds GRDB with a custom SQLite build.
-`GRDBProfiling.xcodeproj`: a project which helps profile GRDB with Instruments. No code here is really precious.
-`GRDBDemoiOS.xcodeproj`, `GRDBCombineDemo.xcodeproj`, `GRDBAsyncDemo.xcodeproj`: the demo apps.
To work with `GRDBCustom.xcodeproj`:
- Make sure Xcode is installed in `/Applications`.
- Run `make SQLiteCustom` in the terminal so that SQLite sources are present.
5.**Run tests**
You can run tests from `GRDB.xcworkspace`, after selecting your scheme (`GRDB` from `GRDB.xcodeproj` or `GRDBCustom` from `GRDBCustom.xcodeproj`).
Before submitting a pull request, please run in the terminal:
```sh
make smokeTest
```
The "smoke tests" perform minimal testing of the system SQLite, SQLCipher, custom SQLite builds, as well as SPM integration.
Before a release, the full test suite must pass:
```sh
make test
```
The full test suite performs many more checks, such as the ability to archive an XCFramework, various installation methods, the demo apps, etc.
6. **Please respect the existing coding style**
- Get familiar with the [Swift API Design Guidelines](https://www.swift.org/documentation/api-design-guidelines/).
- Spaces, not tabs.
- Whitespace-only lines are not trimmed.
- Documentation comments are hard-wrapped at column 76 (Xcode > Preferences > Text Editing > Display > [X] Page guide at column: 76).
- No Swiftlint warning after a build.
7. **Please provide documentation for your changes**
GRDB documentation is provided as a DocC reference, and guides ([README.md](README.md) and the [Documentation](Documentation) folder).
Please keep the reference and the guides up-to-date. To control the quality of your DocC reference documentation, close the workspace, open `Package.swift` in Xcode, and use Product > Build Documentation.
GRDB is "documentation-driven", which means that nothing ships until it is supported by documentation that makes sense. Documentation makes sense when someone who is not you is able to figure out what the purpose of your contribution is, how to use it, and what its caveats and corner cases are. When the documentation is hard to write, or reveals too many caveats, it is a sign that the api needs to be fixed.
8. **Open a pull request with your changes (targeting the `development` branch)!**
9.**If you are granted push access to the repository**, check [ReleaseProcess.md](Documentation/ReleaseProcess.md) in order to publish a new GRDB version.
## Answer issues and contribute to discussions
Answering [issues](https://github.com/groue/GRDB.swift/issues), participating in [discussions](https://github.com/groue/GRDB.swift/discussions) and in the [forum](https://forums.swift.org/c/related-projects/grdb/36) is a great way to help, get familiar with the library, and shape its direction.
## Financial support and sponsoring
GRDB is free, and openly developed by its contributors, in their free time, according to their will, needs, and availability. It is not controlled by any company.
Support is free as well, as long as it happens publicly, and is available to everyone as well as internet search engines. This excludes the private channels of social networks, closed environments such as Slack, etc.
When you have specific development or support needs, please send an email to [Gwendal Roué](mailto:gr@pierlis.com) so that we can enter a regular business relationship through the [Pierlis](http://pierlis.com/) company, based in Paris, France.
You can also [sponsor @groue via GitHub](https://github.com/sponsors/groue).
[Contribute to the GRDB codebase]: #contribute-to-the-grdb-codebase
[Answer issues and contribute to discussions]: #answer-issues-and-contribute-to-discussions
[Financial support and sponsoring]: #financial-support-and-sponsoring
This method returns a publisher that completes after database values have been asynchronously fetched.
```swift
//DatabasePublishers.Read<[Player]>
letplayers=dbQueue.readPublisher{dbin
tryPlayer.fetchAll(db)
}
```
Any attempt at modifying the database completes subscriptions with an error.
When you use a [database queue] or a [database snapshot], the read has to wait for any concurrent database access performed by this queue or snapshot to complete.
When you use a [database pool], reads are generally non-blocking, unless the maximum number of concurrent reads has been reached. In this case, a read has to wait for another read to complete. That maximum number can be [configured].
This publisher can be subscribed from any thread. A new database access starts on every subscription.
The fetched value is published on the main queue, unless you provide a specific [scheduler] to the `receiveOn` argument.
This publisher can be subscribed from any thread. A new database access starts on every subscription.
It completes on the main queue, unless you provide a specific [scheduler] to the `receiveOn` argument.
When you use a [database pool], and your app executes some database updates followed by some slow fetches, you may profit from optimized scheduling with [`writePublisher(receiveOn:updates:thenRead:)`]. See below.
This method returns a publisher that completes after database updates have been successfully executed inside a database transaction, and values have been subsequently fetched:
```swift
//DatabasePublishers.Write<Int>
letnewPlayerCount=dbQueue.writePublisher(
updates:{dbintryPlayer(...).insert(db)},
thenRead:{db,_intryPlayer.fetchCount(db)})
```
It publishes exactly the same values as [`writePublisher(receiveOn:updates:)`]:
The difference is that the last fetches are performed in the `thenRead` function. This function accepts two arguments: a readonly database connection, and the result of the `updates` function. This allows you to pass information from one function to the other (it is ignored in the sample code above).
When you use a [database pool], this method applies a scheduling optimization: the `thenRead` function sees the database in the state left by the `updates` function, and yet does not block any concurrent writes. This can reduce database write contention.
When you use a [database queue], the results are guaranteed to be identical, but no scheduling optimization is applied.
This publisher can be subscribed from any thread. A new database access starts on every subscription.
It completes on the main queue, unless you provide a specific [scheduler] to the `receiveOn` argument.
# Database Observation
Database Observation publishers are based on [ValueObservation] and [DatabaseRegionObservation]. Please refer to their documentation for more information. If your application needs change notifications that are not built as Combine publishers, check the general [Database Changes Observation] chapter.
- [`ValueObservation.publisher(in:scheduling:)`]
- [`SharedValueObservation.publisher()`]
- [`DatabaseRegionObservation.publisher(in:)`]
#### `ValueObservation.publisher(in:scheduling:)`
[ValueObservation] tracks changes in database values. You can turn it into a Combine publisher:
```swift
letobservation=ValueObservation.tracking{dbin
tryPlayer.fetchAll(db)
}
//Apublisherwithoutput[Player]andfailureError
letpublisher=observation.publisher(in:dbQueue)
```
This publisher has the same behavior as ValueObservation:
- It notifies an initial value before subsequent changes.
- It may coalesce subsequent changes into a single notification.
- It may notify consecutive identical values. You can filter out the undesired duplicates with the `removeDuplicates()` Combine operator, but we suggest you have a look at the [removeDuplicates()](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/removeduplicates()) GRDB operator also.
- It only completes when it is cancelled.
- By default, it notifies the initial value, as well as subsequent changes and errors, on the main thread, asynchronously.
This can be configured with the `scheduling` argument. It does not accept a Combine scheduler, but a [ValueObservationScheduler](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservationscheduler).
For example, the `.immediate` scheduler makes sure the initial value is notified immediately when the publisher is subscribed. It can help your application update the user interface without having to wait for any asynchronous notifications:
```swift
// Immediate notification of the initial value
let cancellable = observation
.publisher(
in: dbQueue,
scheduling: .immediate) // <-
.sink(
receiveCompletion: { completion in ... },
receiveValue: { (players: [Player]) in print("Fresh players: \(players)") })
// <- here "fresh players" is already printed.
```
Note that the `.immediate` scheduler requires that the publisher is subscribed from the main thread. It raises a fatal error otherwise.
#### `SharedValueObservation.publisher()`
[SharedValueObservation] tracks changes in database values. You can turn it into a Combine publisher:
```swift
let sharedObservation = ValueObservation
.tracking { db in try Player.fetchAll(db) }
.shared(in: dbQueue)
// A publisher with output [Player] and failure Error
let publisher = sharedObservation.publisher()
```
This publisher has the same behavior as SharedValueObservation.
#### `DatabaseRegionObservation.publisher(in:)`
[DatabaseRegionObservation] notifies all transactions that impact a tracked database region. You can turn it into a Combine publisher:
```swift
let request = Player.all()
let observation = DatabaseRegionObservation.tracking(request)
// A publisher with output Database and failure Error
let publisher = observation.publisher(in: dbQueue)
```
This publisher can be created and subscribed from any thread. It delivers database connections in a "protected dispatch queue", serialized with all database updates. It only completes when a database error happens.
```swift
let request = Player.all()
let cancellable = DatabaseRegionObservation
.tracking(request)
.publisher(in: dbQueue)
.sink(
receiveCompletion: { completion in ... },
receiveValue: { (db: Database) in
print("Players have changed.")
})
try dbQueue.write { db in
try Player(name: "Arthur").insert(db)
try Player(name: "Barbara").insert(db)
}
// Prints "Players have changed."
try dbQueue.write { db in
try Player.deleteAll(db)
}
// Prints "Players have changed."
```
See [DatabaseRegionObservation] for more information.
## Combine and Data Consistency
When you compose database publishers together with Combine operators such as `combineLatest` or `zip`, you lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
This is because each database publisher is isolated from others: each one of them sees its own state of the database. Whenever some database change is interleaved between publisher operations, publishers will process or publish values that may not fit well together.
In other words, whenever you need to perform some database access or observation that depends on some database invariant, make sure you define one and only one database publisher instead of combining several publishers. This is how you will prevent concurrent database writes from messing with your app, and introducing bugs.
To this end, remember that *all database publishers can perform several requests*.
In the example below, we are totally sure that the published `HallOfFame` values will never contain inconsistent values, because it is produced by one and only one publisher:
**Common table expressions** (CTEs) can generally be seen as *SQL views that you define on the fly*.
A certain level of familiarity with SQL databases is helpful before you dive into this guide. The starting point is obviously the [SQLite documentation](https://sqlite.org/lang_with.html). Many CTE tutorials exist online as well, including [this good one](https://blog.expensify.com/2015/09/25/the-simplest-sqlite-common-table-expression-tutorial/).
In this guide, you will learn how to:
- [Define Common Table Expressions]
- [Embed Common Table Expressions in Requests]
- [Fetch Values From Common Table Expressions]
- Join CTEs with [Associations to Common Table Expressions]
> **Note**: most code examples will be trivial, and not very "useful". This is because the goal of this guide is to stay focused on the GRDB support for CTEs. Rich setup would just be distracting. So bring your own good ideas with you!
## Define Common Table Expressions
You will create a `CommonTableExpression` definition first. Choose a **name**, and a **request** that provides the content of the common table expression.
The CTE name is like a regular table name: pick one that does not conflict with the names of existing tables.
The CTE request can be provided as a [query interface request]:
```swift
//WITHplayerNameAS(SELECTnameFROMplayer)...
letplayerNameCTE=CommonTableExpression(
named:"playerName",
request:Player.select(\.name))
```
You can feed a CTE with raw SQL as well (second and third examples use [SQL Interpolation]):
```swift
letname="O'Brien"
//WITHplayerNameAS(SELECT'O''Brien')...
letplayerNameCTE=CommonTableExpression(
named:"playerName",
sql:"SELECT ?",arguments:[name])
//WITHplayerNameAS(SELECT'O''Brien')...
letplayerNameCTE=CommonTableExpression(
named:"playerName",
literal:"SELECT \(name)")
//WITHplayerNameAS(SELECT'O''Brien')...
letrequest=SQLRequest("SELECT \(name)")
letplayerNameCTE=CommonTableExpression(
named:"playerName",
request:request)
```
All CTEs can be provided with explicit column names:
```swift
//WITHpair(a,b)AS(SELECT1,2)...
letpairCTE=CommonTableExpression(
named:"pair",
columns:["a","b"],
sql:"SELECT 1, 2")
```
Recursive CTEs need the `recursive` flag. The example below selects all integers between 1 and 1000:
> **Note**: many recursive CTEs use the `UNION ALL` SQL operator. The query interface does not provide any Swift support for it, so you'll generally have to write SQL in your definitions of recursive CTEs.
## Embed Common Table Expressions in Requests
A typical SQLite query that uses a common table expression first *defines* the CTE and then *uses* the CTE by mentioning its table name. We'll see below Swift apis that match those two steps.
We will use the (simple) query below as a target. It is the query we'll want to generate in this chapter. It defines a CTE, and uses it in a subquery:
```sql
WITHplayerNameAS(SELECT'O''Brien')
SELECT*FROMplayer
WHEREname=(SELECT*FROMplayerName)
```
We first build a `CommonTableExpression`:
```swift
letname="O'Brien"
letplayerNameCTE=CommonTableExpression(
named:"playerName",
literal:"SELECT \(name)")
```
We can then embed the definition of the CTE in a [query interface request] by calling the `with(_:)` method:
```swift
//WITHplayerNameAS(SELECT'O''Brien')
//SELECT*FROMplayer...
letrequest=Player
.with(playerNameCTE)...
```
And we can then filter the `player` table with a subquery:
```swift
//WITHplayerNameAS(SELECT'O''Brien')
//SELECT*FROMplayer
//WHEREname=(SELECT*FROMplayerName)
letrequest=Player
.with(playerNameCTE)
.filter{$0.name==playerNameCTE.all()}
```
> **Note**: the `with(_:)` method can be called as many times as there are common table expressions in your request.
>
> **Note**: the `with(_:)` method can be called at any time, like all request methods: `Player.with(...).filter(...).with(...)`.
>
> **Note**: the `with(_:)` method replaces any previously embedded CTE that has the same table name. This allows you to embed the same CTE several times if you feel like it.
>
> **Note**: the `CommonTableExpression.all()` method builds a regular [query interface request] for the content of the CTE (like `SELECT * FROM <cte name>`, not to be confused with the request that was used to define the CTE). You can filter this request, sort it, etc, like all query interface requests:
In the previous chapter, a common table expression was embedded as a subquery, with the `CommonTableExpression.all()` method.
`cte.all()` builds a regular [query interface request] that you can filter, sort, etc, like all query interface requests.
You can also fetch from `cte.all()`, as long as the request is given the definition of the CTE: `cte.all().with(cte)`. In SQL, this would give: `WITH cte AS (...) SELECT * FROM cte`:
This request, of type `QueryInterfaceRequest<Row>`, can fetch raw database [rows](../README.md#row-queries):
```swift
letcte=CommonTableExpression(...)
letrequest=cte.all().with(cte)
letrows=tryrequest.fetchAll(db)//[Row]
```
In order to fetch something else, such as simple [values](../README.md#value-queries), or custom [records](../README.md#records), you have two possible options:
1. Use the `asRequest(of:)` method:
```swift
let cte = CommonTableExpression(...)
let request = cte.all().with(cte).asRequest(of: Player.self)
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~
let players = try request.fetchAll(db) // [Player]
```
2. Provide the fetched type to the cte itself:
```swift
let cte = CommonTableExpression<Player>(...)
// ~~~~~~~~
let request = cte.all().with(cte)
let players = try request.fetchAll(db) // [Player]
```
## Associations to Common Table Expressions
GRDB [associations] define "to-one" and "to-many" relationships between two database tables. Here we will define associations between regular tables and common table expressions.
We recommend familiarity with the "joining methods", described in [Joining And Prefetching Associated Records]:
```swift
// SELECT parent.* FROM parent LEFT JOIN child ON ...
Parent.joining(optional: childAssociation)
// SELECT parent.* FROM parent JOIN child ON ...
Parent.joining(required: childAssociation)
// SELECT parent.*, child.* FROM parent LEFT JOIN child ON ...
Parent.including(optional: childAssociation)
// SELECT parent.*, child.* FROM parent JOIN child ON ...
Parent.including(required: childAssociation)
```
> **Note**: common table expressions currently only define "to-one" associations, so the `including(all:)` joining method is unavailable.
CTE associations are generally built with the `association(to:on:)` method, which needs:
- The two sides of the association: a `CommonTableExpression` instance, and another CTE or a type that conforms to the [TableRecord] protocol.
- A function that returns the condition that joins the two sides of the association.
The condition function plays the same role as the **foreign key** that defines regular table [associations] such as **BelongsTo** or **HasMany**. It accepts two [TableAlias], from which you can build a joining expression:
For example:
```swift
// An association from LeftRecord to rightCTE
let rightCTE = ...
let association = LeftRecord.association(
to: rightCTE,
on: { left, right in
left[Column("x")] == right[Column("y")]
})
```
Now this association can be used with a joining method:
```swift
// WITH rightCTE AS (...)
// SELECT leftRecord.*, rightCTE.*
// FROM leftRecord
// JOIN rightCTE ON leftRecord.x = rightCTE.y
LeftRecord
.with(rightCTE)
.including(required: association)
```
### CTE Association Example: a Chat App
As an example, let's build the classic main screen of a chat application: a list of all latest messages from all conversations.
The database schema of the chat app contains a `chat` and a `message` table. The application defines the following records:
To feed the main app screen, we want to fetch a list of `ChatInfo` records:
```swift
struct ChatInfo: Decodable, FetchableRecord {
/// The chat
var chat: Chat
/// The latest chat message, if any
var latestMessage: Message?
}
```
The SQL request that we want to run is below. It uses an SQLite-specific [special processing](https://sqlite.org/lang_select.html) of `MAX()` that helps the selection of latest messages from all chats:
```sql
WITH latestMessage AS
(SELECT *, MAX(date) FROM message GROUP BY chatID)
SELECT chat.*, latestMessage.*
FROM chat
LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
ORDER BY latestMessage.date DESC
```
We start by defining the CTE request, which loads the latest messages of all chats:
```swift
// SELECT *, MAX(date) FROM message GROUP BY chatID
let latestMessageRequest = Message
.annotated { max($0.date) }
.group(\.chatId)
```
We can now define the CTE for the latest messages:
```swift
// WITH latestMessage AS
// (SELECT *, MAX(date) FROM message GROUP BY chatID)
let latestMessageCTE = CommonTableExpression<Message>(
named: "latestMessage",
request: latestMessageRequest)
```
The association from a chat to its latest message follows:
```swift
// ... JOIN latestMessage ON chat.id = latestMessage.chatID
let latestMessage = Chat.association(
to: latestMessageCTE,
on: { chat, latestMessage in
chat.id == latestMessage.chatId
})
.order(\.date.desc)
```
The final request can now be defined:
```swift
// WITH latestMessage AS
// (SELECT *, MAX(date) FROM message GROUP BY chatID)
// SELECT chat.*, latestMessage.*
// FROM chat
// LEFT JOIN latestMessage ON chat.id = latestMessage.chatID
// ORDER BY latestMessage.date DESC
let request = Chat
.with(latestMessageCTE)
.including(optional: latestMessage)
.asRequest(of: ChatInfo.self)
```
And we can fetch the data that feeds our application screen:
```swift
let chatInfos: [ChatInfo] = try dbQueue.read { db in
try request.fetchAll(db)
}
```
> :bulb: **Tip**: the joining methods are generally type-safe: they won't allow you to join apples to oranges. This works when associations have a *precise* type. In this context, anonymous `CommonTableExpression` CTEs can work against type safety. When you want to define associations between several CTEs, and make sure the compiler will notice wrong uses of those associations, tag your common table expressions with an explicit type: `CommonTableExpression<SomeType>`.
>
> To do so, you can use an existing record type, or an ad-hoc enum. For example:
>
> ```swift
> enum CTE1 { }
> let cte1 = CommonTableExpression<CTE1>(...)
>
> enum CTE2 { }
> let cte2 = CommonTableExpression<CTE2>(...)
>
> let assoc1 = BaseRecord.association(to: cte1, on: ...) // from BaseRecord to CTE1
> let assoc2 = cte1.association(to: cte2, on: ...) // from CTE1 to CTE2
> let assoc3 = cte2.association(to: FarRecord.self, on: ...) // from CTE2 to FarRecord
>
> // WITH ...
> // SELECT base.* FROM base
> // JOIN cte1 ON ...
> // JOIN cte2 ON ...
> // JOIN far ON ...
> let request = BaseRecord
> .with(cte1).with(cte2)
> .joining(required: assoc1 // OK
> .joining(required: assoc2 // OK
> .joining(required: assoc3))) // OK
>
> // Compiler error
> let request = BaseRecord
> .joining(required: assoc2) // Not OK
> .joining(required: assoc3) // Not OK
> ```
[query interface request]: ../README.md#requests
[query interface requests]: ../README.md#requests
[SQLRequest]: ../README.md#custom-requests
[SQLiteral]: SQLInterpolation.md
[SQL Interpolation]: SQLInterpolation.md
[associations]: AssociationsBasics.md
[Joining And Prefetching Associated Records]: AssociationsBasics.md#joining-and-prefetching-associated-records
[Define Common Table Expressions]: #define-common-table-expressions
[Embed Common Table Expressions in Requests]: #embed-common-table-expressions-in-requests
[Fetch Values From Common Table Expressions]: #fetch-values-from-common-table-expressions
[Associations to Common Table Expressions]: #associations-to-common-table-expressions
By default, GRDB uses the version of SQLite that ships with the target operating system.
**You can build GRDB with a custom build of [SQLite 3.24.0](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.47.2](https://www.sqlite.org/changes.html).**
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](../../../#full-text-search), and [SQLite Pre-Update Hooks](../../../#support-for-sqlite-pre-update-hooks).
A custom SQLite build can activate extra SQLite features, and extra GRDB features as well, such as support for the [FTS5 full-text search engine](FullTextSearch.md), and [SQLite Pre-Update Hooks](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/transactionobserver).
GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfalling/SQLiteLib), which uses the same SQLite configuration as the one used by Apple in its operating systems, and lets you add extra compilation options that leverage the features you need.
> Warning: The technique described here is not compatible with the Swift Package Manager (SPM). It will create [build issues](https://github.com/groue/GRDB.swift/issues/1709) with SPM companion libraries such as [GRDBQuery](https://github.com/groue/GRDBQuery) or [GRDBSnapshotTesting](https://github.com/groue/GRDBSnapshotTesting).
**To install GRDB with a custom SQLite build:**
1. Clone the GRDB git repository, checkout the latest tagged version, and download SQLite sources:
1. Clone the GRDB git repository, checkout the latest tagged version:
```sh
cd [GRDB directory]
git checkout v3.2.0
git checkout [latest tag]
git submodule update --init SQLiteCustom/src
````
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5` and `SQLITE_ENABLE_PREUPDATE_HOOK`.
```
2. Choose your [extra compilation options](https://www.sqlite.org/compile.html). For example, `SQLITE_ENABLE_FTS5`, `SQLITE_ENABLE_PREUPDATE_HOOK`.
It is recommended that you enable the `SQLITE_ENABLE_SNAPSHOT` option. It allows GRDB to optimize [ValueObservation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation) when you use a [Database Pool](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool).
3. Create a folder named `GRDBCustomSQLite` somewhere in your project directory.
4. Create four files in the `GRDBCustomSQLite` folder:
- `SQLiteLib-USER.xcconfig`: this file sets the extra SQLite compilation flags.
```xcconfig
// As many -D options as there are custom SQLite compilation options
// Note: there is no space between -D and the option name.
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
Modify the top of the `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
5. Embed the `GRDBCustom.xcodeproj` project in your own project.
6. Add the `GRDBCustomSQLiteOSX` or `GRDBCustomSQLiteiOS` target in the **Target Dependencies** section of the **Build Phases** tab of your **application target**.
6. Add the `GRDBCustom` target in the **Target Dependencies** section of the **Build Phases** tab of your **application target**.
7. Add the `GRDBCustomSQLite.framework` from the targetted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
7. Add the `GRDBCustom.framework` from the targeted platform to the **Embedded Binaries** section of the **General** tab of your **application target**.
8. Add a Run Script phase for your target in the **Pre-actions** section of the **Build** tab of your **application scheme**:
The path should be the path to your `GRDBCustomSQLite-INSTALL.sh` file.
Select your application target in the "Provide build settings from" menu.
9. Check the "Shared" checkbox of your application scheme (this lets you commit the pre-action in your Version Control System).
10. If you have enabled "Hardened Runtime" for your target (**Build Settings**/**Signing**) then you may need to check **Disable Library Validation** under the **Hardened Runtime** section of the **Signing & Capabilities** tab.
(The build error without this exception is "Library not loaded ... different Team IDs")
Now you can use GRDB with your custom SQLite build:
**GRDBDemo demonstrates how GRDB can fuel a SwiftUI application.**
> **Note**: This demo app is not a project template. Do not copy it as a starting point for your application. Instead, create a new project, choose a GRDB [installation method](../../../README.md#installation), and use the demo as inspiration.
The topics covered in this demo are:
- How to set up 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).
- How to apply the recommendations of [Recommended Practices for Designing Record Types](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/recordrecommendedpractices).
- How to feed SwiftUI previews with a transient database.
**Files of interest:**
- [GRDBDemoApp.swift](GRDBDemo/GRDBDemoApp.swift)
`GRDBDemoApp` feeds the SwiftUI app with a database, through the SwiftUI environment.
`AppDatabase` is the type that grants database access. It uses [DatabaseMigrator](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasemigrator) in order to set up the database schema, and provides methods that read and write.
`AppDatabase` is [tested](GRDBDemoTests/AppDatabaseTests.swift).
This file instantiates `AppDatabase` instances for the various needs of the project: one database on disk for the application, and in-memory databases for SwiftUI previews.
`Player` is a [Record](../../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all the advantages of [Codable Records](../../../README.md#codable-records).
`PlayersNavigationView` is the main navigation view of the application. It instantiates a `PlayerListModel` from the `AppDatabase` stored in the SwiftUI environment.
[GRDBDemo] demonstrates how GRDB can fuel a SwiftUI application.
See also the demo apps of the [GRDBQuery] package: they use the `@Query` property wrapper that helps SwiftUI views automatically update their content when the database changes.
**[FTS5](https://www.sqlite.org/fts5.html) is an extensible full-text search engine.**
GRDB lets you define your own custom FST5 tokenizers, and extend SQLite built-in tokenizers. Possible use cases are:
GRDB lets you define your own custom FTS5 tokenizers, and extend SQLite built-in tokenizers. Possible use cases are:
- Have "fi" match the ligature "fi" (U+FB01)
- Have "first" match "1st"
@@ -29,13 +29,13 @@ GRDB lets you define your own custom FST5 tokenizers, and extend SQLite built-in
**A Tokenizer splits text into tokens**. For example, a tokenizer can split "SQLite is a database engine" into the five tokens "SQLite", "is", "a", "database", and "engine".
FTS5 use tokenizers to tokenize both indexed documents and search patterns. **A match between a document and a search pattern happens when both produce *identical* tokens.**
FTS5 uses tokenizers to tokenize both indexed documents and search patterns. **A match between a document and a search pattern happens when both produce *identical* tokens.**
All SQLite [built-in tokenizers](https://www.sqlite.org/fts5.html#tokenizers) tokenize both "SQLite" and "sqlite" into the common lowercase token "sqlite". This is why they are case-insensitive. Generally speaking, different tokenizers achieve different matching by applying different transformations to the input text.
- The [ascii](https://www.sqlite.org/fts5.html#ascii_tokenizer) tokenizer turns all ASCII characters to lowercase. "SQLite is a database engine" gives "sqlite", "is", "a", "database", and "engine". The query "SQLITE DATABASE" will match, because its tokens "sqlite" and "database" are found in the document.
- The [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer remove diacritics from latin characters. Unlike the ascii tokenizer, it will match "Jérôme" with "Jerome", as both produce the same "jerome" token.
- The [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer removes diacritics from latin characters. Unlike the ascii tokenizer, it will match "Jérôme" with "Jerome", as both produce the same "jerome" token.
- The [porter](https://www.sqlite.org/fts5.html#porter_tokenizer) tokenizer turns English words into their root: "database engine" gives the "databas" and "engin" tokens. The query "database engines" will match, because it produces the same tokens.
@@ -43,7 +43,7 @@ However, built-in tokenizers don't match "first" with "1st", because they produc
Nor do they match "Grossmann" with "Großmann", because they produce the different "grossmann" and "großmann" tokens.
Custom tokenizers help dealing with these situations. We'll see how to match "Grossmann" and "Großmann" by tokenizing them into "grossmann" (see [latin script](#example-latin-script)). We'll also see how to have "first" and "1st" emit *synonym tokens*, so that they can match too (see [synonyms](#example-synonyms)).
Custom tokenizers help deal with these situations. We'll see how to match "Grossmann" and "Großmann" by tokenizing them into "grossmann" (see [latin script](#example-latin-script)). We'll also see how to have "first" and "1st" emit *synonym tokens*, so that they can match too (see [synonyms](#example-synonyms)).
## The Tokenizer Protocols
@@ -54,7 +54,7 @@ GRDB lets you use and define FTS5 tokenizers through three protocols:
- [FTS5CustomTokenizer](#fts5customtokenizer): the low-level protocol that lets custom tokenizers use the raw [FTS5 C API](https://www.sqlite.org/fts5.html#custom_tokenizers).
- [FTS5WrapperTokenizer](#fts5wrappertokenizer): the high-level protocol for custom tokenizers that post-processes the tokens produced by another FTS5Tokenizer.
- [FTS5WrapperTokenizer](#fts5wrappertokenizer): the high-level protocol for custom tokenizers that post-process the tokens produced by another FTS5Tokenizer.
## Using a Custom Tokenizer
@@ -66,10 +66,14 @@ Once you have a custom tokenizer type that adopts [FTS5CustomTokenizer](#fts5cus
@@ -78,10 +82,10 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
}
```
The full-text table can be fed and queried in [a regular way](../../../#full-text-search):
The full-text table can be fed and queried in [a regular way](FullTextSearch.md):
```swift
trydb.execute("INSERT INTO documents VALUES (?)",arguments:["..."])
trydb.execute(sql:"INSERT INTO documents VALUES (?)",arguments:["..."])
tryDocument(content:"...").insert(db)
letpattern=FTS5Pattern(matchingAnyTokenIn:"...")
@@ -91,7 +95,7 @@ let documents = try Document.matching(pattern).fetchAll(db)
## FTS5Tokenizer
**FST5Tokenizer** is the protocol for all FTS5 tokenizers.
**FTS5Tokenizer** is the protocol for all FTS5 tokenizers.
It only requires a tokenization method that matches the low-level `xTokenize` C function documented at https://www.sqlite.org/fts5.html#custom_tokenizers. We'll discuss it more when describing custom tokenizers.
@@ -157,7 +161,7 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
FTS5CustomTokenizer inherits from [FTS5Tokenizer](#fts5tokenizer), and performs tokenization with its `tokenize(context:tokenization:pText:nText:tokenCallback:)` method. This low-level method matches the `xTokenize` C function documented at https://www.sqlite.org/fts5.html#custom_tokenizers.
This method arguments are:
This method's arguments are:
-`context`: An opaque pointer that is the first argument to the `tokenCallback` function
-`tokenization`: The reason why FTS5 is requesting tokenization.
@@ -171,18 +175,18 @@ This method arguments are:
-`iStart`: Byte offset of token within input text
-`iEnd`: Byte offset of end of token within input text
Since tokenization is hard, and pointers to byte buffers uneasy to deal with, you may enjoy the [FTS5WrapperTokenizer](#fts5wrappertokenizer) protocol.
Since tokenization is hard, and pointers to byte buffers difficult to deal with, you may enjoy the [FTS5WrapperTokenizer](#fts5wrappertokenizer) protocol.
## FTS5WrapperTokenizer
**FTS5WrapperTokenizer** is the high-level protocol for your custom tokenizers. It provides a default implementation for the low-level `tokenize(context:tokenization:pText:nText:tokenCallback:)` method, so that the adopting type does not have to deal with raw byte buffers of the raw [FTS5 C API](https://www.sqlite.org/fts5.html#custom_tokenizers).
A FTS5WrapperTokenizer lets the hard tokenization job to another tokenizer, the "wrapped tokenizer", and post-processes the tokens produced by this wrapped tokenizer.
An FTS5WrapperTokenizer leaves the hard tokenization job to another tokenizer, the "wrapped tokenizer", and post-processes the tokens produced by this wrapped tokenizer.
As all custom tokenizers, wrapper tokenizers must have a name:
Like all custom tokenizers, wrapper tokenizers must have a name:
```swift
finalclassMyTokenizer:FTS5WrapperTokenizer{
@@ -203,7 +207,7 @@ The `wrappedTokenizer` property is the mandatory wrapped tokenizer. You instanti
```swift
finalclassMyTokenizer:FTS5WrapperTokenizer{
letwrappedTokenizer:FTS5Tokenizer
letwrappedTokenizer:anyFTS5Tokenizer
init(db:Database,arguments:[String])throws{
//Wraptheunicode61tokenizer
@@ -232,11 +236,11 @@ final class MyTokenizer : FTS5WrapperTokenizer {
The token argument is a token produced by the wrapped tokenizer, ready to be ignored, modified, or multiplied into several [synonyms](#example-synonyms).
The tokenization parameter tells the reason why tokens are produced, if FTS5 is tokenizing a document, or a search pattern. Some tokenizers may produce different tokens depending on this parameter.
The tokenization parameter tells the reason why tokens are produced: whether FTS5 is tokenizing a document, or a search pattern. Some tokenizers may produce different tokens depending on this parameter.
Finally, the tokenCallback is a function you call to output a custom token.
There are a two rules to observe when implementing the accept method:
There are two rules to observe when implementing the accept method:
1. Errors thrown by the tokenCallback function must not be caught (they notify that FTS5 requires the tokenization process to stop immediately).
2. The flags parameter should be given unmodified to the tokenCallback function along with the custom token, unless you union it with the `.colocated` flag when the tokenizer produces [synonyms](#example-synonyms).
@@ -251,7 +255,7 @@ For example, your custom tokenizer can wrap [unicode61](https://www.sqlite.org/f
```swift
finalclassMyTokenizer:FTS5WrapperTokenizer{
staticletname="custom"
letwrappedTokenizer:FTS5Tokenizer
letwrappedTokenizer:anyFTS5Tokenizer
init(db:Database,arguments:[String])throws{
ifarguments.isEmpty{
@@ -296,16 +300,16 @@ try db.create(virtualTable: "documents", using: FTS5()) { t in
The topic of synonyms is documented at https://www.sqlite.org/fts5.html#synonym_support, which describes several methods. You should carefully read this documentation, and pick the method you prefer.
In the example below, we'll pick method (3), and implement a tokenizer that adds multiple synonyms for a single term to the FTS index. Using this method, when tokenizing document text, the tokenizer provides multiple synonyms for each token. So that when a document such as "I won first place" is tokenized, entries are added to the FTS index for "i", "won", "first", "1st" and "place".
In the example below, we'll pick method (3), and implement a tokenizer that adds multiple synonyms for a single term to the FTS index. Using this method, when tokenizing document text, the tokenizer provides multiple synonyms for each token. So when a document such as "I won first place" is tokenized, entries are added to the FTS index for "i", "won", "first", "1st" and "place".
We'll also take care of the SQLite advice:
We'll also follow the SQLite advice:
> When using methods (2) or (3), it is important that the tokenizer only provide synonyms when tokenizing document text or query text, not both. Doing so will not cause any errors, but is inefficient.
```swift
finalclassSynonymsTokenizer:FTS5WrapperTokenizer{
staticletname="synonyms"
letwrappedTokenizer:FTS5Tokenizer
letwrappedTokenizer:anyFTS5Tokenizer
letsynonyms:[Set<String>]=[["first","1st"]]
init(db:Database,arguments:[String])throws{
@@ -313,7 +317,7 @@ final class SynonymsTokenizer : FTS5WrapperTokenizer {
@@ -346,18 +350,18 @@ Languages that use the [latin script](https://en.wikipedia.org/wiki/Latin_script
Full-text search in such a corpus often needs input tolerance, so that "encyclopaedia" can match "Encyclopædia", "Grossmann", "Großmann", and "Jerome", "Jérôme".
German has something specific in that both "Mueller" and "Muller" should match "Müller", when "Bauer" should not match "Baur" (only "ü" accepts both "u" and "ue"). A pull request that adds a chapter about German will be welcome.
German has something specific in that both "Mueller" and "Muller" should match "Müller", while "Bauer" should not match "Baur" (only "ü" accepts both "u" and "ue"). A pull request that adds a chapter about German will be welcome.
A custom FTS5 tokenizer lets you provide fuzzy latin matching: after "Grossmann", "Großmann", and "GROSSMANN" have all been turned into "grossmann", they will all match together.
We'll wrap the built-in [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer (the one that knows how to split text on spaces and punctuations), and transform its tokens into their bare lowercase ascii form.
We'll wrap the built-in [unicode61](https://www.sqlite.org/fts5.html#unicode61_tokenizer) tokenizer (the one that knows how to split text on spaces and punctuation), and transform its tokens into their bare lowercase ascii form.
The tokenizer wrapping is provided by the [FTS5WrapperTokenizer](#fts5wrappertokenizer) protocol. The string transformation is provided by the [String.applyingTransform](https://developer.apple.com/reference/swift/string/1643133-applyingtransform) method:
@@ -371,8 +375,6 @@ final class LatinAsciiTokenizer : FTS5WrapperTokenizer {
}
```
> :point_up: **Note**: String.applyingTransform is not available before iOS 9.0 and macOS 10.11. Use the Core Foundation function [CFStringTransform](https://developer.apple.com/reference/corefoundation/1542411-cfstringtransform) instead.
Remember to register LatinAsciiTokenizer before using it:
FetchedRecordsController has been removed in GRDB 5.
See [Database Observation](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseobservation) for other ways to observe the database.
- **Custom Tokenizers**: [FTS5](FTS5Tokenizers.md). Leverage extra full-text features such as synonyms or stop words. Avoid [unicode gotchas](#unicode-full-text-gotchas).
- **Sample Code**: [WWDC Companion](https://github.com/groue/WWDCCompanion), an iOS app that stores, displays, and lets the user search the WWDC 2016 sessions.
## Choosing the Full-Text Engine
**SQLite supports three full-text engines: [FTS3, FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html).**
Generally speaking, FTS5 is better than FTS4 which improves on FTS3. But this does not really tell which engine to choose for your application. Instead, make your choice depend on:
- **The full-text features needed by the application**:
| **Ranking** (sort results by relevance) | ¹ | ¹ | X |
| **Snippets** (display a few words around a match) | X | X | X |
¹ Requires extra setup, possibly hard to implement.
² Requires a [custom tokenizer](FTS5Tokenizers.md).
For a full feature list, read the SQLite documentation. Some missing features can be achieved with extra application code.
- **The speed versus disk space constraints.** Roughly speaking, FTS4 and FTS5 are faster than FTS3, but use more space. Only FTS4 supports content compression.
- **The location of the indexed text in your database schema.** Only FTS4 and FTS5 support "contentless" and "external content" tables.
- See [FTS3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
> **Note**: In case you were still wondering, it is recommended to read the SQLite documentation: [FTS3 & FTS4](https://www.sqlite.org/fts3.html) and [FTS5](https://www.sqlite.org/fts5.html).
## Create FTS3 and FTS4 Virtual Tables
**FTS3 and FTS4 full-text tables store and index textual content.**
Create tables with the `create(virtualTable:options:using:_:)` method:
**All columns in a full-text table contain text.** If you need to index a table that contains other kinds of values, you need an ["external content" full-text table](#external-content-full-text-tables).
You can specify a [tokenizer](#fts3-and-fts4-tokenizers):
The `content` option is involved in "contentless" and "external content" full-text tables. GRDB can help you define full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
See [SQLite documentation](https://www.sqlite.org/fts3.html) for more information.
## FTS3 and FTS4 Tokenizers
**A tokenizer defines what "matching" means.** Depending on the tokenizer you choose, full-text searches won't return the same results.
SQLite ships with three built-in FTS3/4 tokenizers: `simple`, `porter` and `unicode61` that use different algorithms to match queries with indexed content:
¹ Don't miss [Unicode Full-Text Gotchas](#unicode-full-text-gotchas)
- **simple**
```swift
try db.create(virtualTable: "book", using: FTS4()) { t in
t.tokenizer = .simple // default
}
```
The default "simple" tokenizer is case-insensitive for ASCII characters. It matches "foo" with "FOO", but not "Jérôme" with "JÉRÔME".
It does not provide stemming, and won't match "databases" with "database".
It does not strip diacritics from latin script characters, and won't match "jérôme" with "jerome".
- **porter**
```swift
try db.create(virtualTable: "book", using: FTS4()) { t in
t.tokenizer = .porter
}
```
The "porter" tokenizer compares English words according to their roots: it matches "database" with "databases", and "frustration" with "frustrated".
It does not strip diacritics from latin script characters, and won't match "jérôme" with "jerome".
- **unicode61**
```swift
try db.create(virtualTable: "book", using: FTS4()) { t in
t.tokenizer = .unicode61()
t.tokenizer = .unicode61(diacritics: .keep)
}
```
The "unicode61" tokenizer is case-insensitive for unicode characters. It matches "Jérôme" with "JÉRÔME".
It strips diacritics from latin script characters by default, and matches "jérôme" with "jerome". This behavior can be disabled, as in the example above.
It does not provide stemming, and won't match "databases" with "database".
See [SQLite tokenizers](https://www.sqlite.org/fts3.html#tokenizer) for more information.
## FTS3 and FTS4 Tokenization
You can tokenize strings when needed:
```swift
// Default tokenization using the `simple` tokenizer:
**Full-text search in FTS3 and FTS4 tables is performed with search patterns:**
- `database` matches all documents that contain "database"
- `data*` matches all documents that contain a word starting with "data"
- `SQLite database` matches all documents that contain both "SQLite" and "database"
- `SQLite OR database` matches all documents that contain "SQLite" or "database"
- `"SQLite database"` matches all documents that contain the "SQLite database" phrase
**Not all search patterns are valid**: they must follow the [Full-Text Index Queries Grammar](https://www.sqlite.org/fts3.html#full_text_index_queries).
The FTS3Pattern type helps you validate patterns, and build valid patterns from untrusted strings (such as strings typed by users):
```swift
struct FTS3Pattern {
init(rawPattern: String) throws
init?(matchingAnyTokenIn string: String)
init?(matchingAllTokensIn string: String)
init?(matchingAllPrefixesIn string: String)
init?(matchingPhrase string: String)
}
```
The first initializer validates your raw patterns against the query grammar, and may throw a [DatabaseError](../README.md#databaseerror):
```swift
// OK: FTS3Pattern
let pattern = try FTS3Pattern(rawPattern: "sqlite AND database")
// DatabaseError: malformed MATCH expression: [AND]
let pattern = try FTS3Pattern(rawPattern: "AND")
```
The other initializers don't throw. They build a valid pattern from any string, **including strings provided by users of your application**. They let you find documents that match any given word, all given words or prefixes, or a full phrase, depending on the needs of your application:
```swift
let query = "SQLite database"
// Matches documents that contain "SQLite" or "database"
let pattern = FTS3Pattern(matchingAnyTokenIn: query)
// Matches documents that contain "SQLite" and "database"
let pattern = FTS3Pattern(matchingAllTokensIn: query)
// Matches documents that contain words that start with "SQLite" and words that start with "database"
let pattern = FTS3Pattern(matchingAllPrefixesIn: query)
// Matches documents that contain "SQLite database"
let pattern = FTS3Pattern(matchingPhrase: query)
```
They return nil when no pattern could be built from the input string:
```swift
let pattern = FTS3Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS3Pattern(matchingAnyTokenIn: "*") // nil
```
FTS3Pattern instances are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
```swift
let documents = try Document.fetchAll(db,
sql: "SELECT * FROM document WHERE content MATCH ?",
arguments: [pattern])
```
Use them in the [query interface](../README.md#the-query-interface):
```swift
// Search in all columns
let documents = try Document.matching(pattern).fetchAll(db)
// Search in a specific column:
let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db)
```
## Create FTS5 Virtual Tables
**FTS5 full-text tables store and index textual content.**
To use FTS5, you'll need a [custom SQLite build] that activates the `SQLITE_ENABLE_FTS5` compilation option.
Create FTS5 tables with the `create(virtualTable:options:using:_:)` method:
```swift
// CREATE VIRTUAL TABLE document USING fts5(content)
try db.create(virtualTable: "document", using: FTS5()) { t in
t.column("content")
}
```
**All columns in a full-text table contain text.** If you need to index a table that contains other kinds of values, you need an ["external content" full-text table](#external-content-full-text-tables).
You can specify a [tokenizer](#fts5-tokenizers):
```swift
// CREATE VIRTUAL TABLE book USING fts5(
// tokenize='porter',
// author,
// title,
// body
// )
try db.create(virtualTable: "book", using: FTS5()) { t in
try db.create(virtualTable: "document", using: FTS5()) { t in
t.column("content")
t.column("uuid").notIndexed()
t.content = "table"
t.contentRowID = "id"
t.prefixes = [2, 4]
t.columnSize = 0
t.detail = "column"
}
```
The `content` and `contentRowID` options are involved in "contentless" and "external content" full-text tables. GRDB can help you define full-text tables that automatically synchronize with their content table. See [External Content Full-Text Tables](#external-content-full-text-tables).
See [SQLite documentation](https://www.sqlite.org/fts5.html) for more information.
## FTS5 Tokenizers
**A tokenizer defines what "matching" means.** Depending on the tokenizer you choose, full-text searches won't return the same results.
SQLite ships with three built-in FTS5 tokenizers: `ascii`, `porter` and `unicode61` that use different algorithms to match queries with indexed content.
```swift
try db.create(virtualTable: "book", using: FTS5()) { t in
// Pick one:
t.tokenizer = .unicode61() // default
t.tokenizer = .unicode61(...)
t.tokenizer = .ascii
t.tokenizer = .porter(...)
}
```
See below some examples of matches:
| content | query | ascii | unicode61 | porter on ascii | porter on unicode61 |
¹ Don't miss [Unicode Full-Text Gotchas](#unicode-full-text-gotchas)
- **unicode61**
```swift
try db.create(virtualTable: "book", using: FTS5()) { t in
t.tokenizer = .unicode61()
t.tokenizer = .unicode61(diacritics: .keep)
}
```
The default "unicode61" tokenizer is case-insensitive for unicode characters. It matches "Jérôme" with "JÉRÔME".
It strips diacritics from latin script characters by default, and matches "jérôme" with "jerome". This behavior can be disabled, as in the example above.
It does not provide stemming, and won't match "databases" with "database".
- **ascii**
```swift
try db.create(virtualTable: "book", using: FTS5()) { t in
t.tokenizer = .ascii()
}
```
The "ascii" tokenizer is case-insensitive for ASCII characters. It matches "foo" with "FOO", but not "Jérôme" with "JÉRÔME".
It does not provide stemming, and won't match "databases" with "database".
It does not strip diacritics from latin script characters, and won't match "jérôme" with "jerome".
- **porter**
```swift
try db.create(virtualTable: "book", using: FTS5()) { t in
t.tokenizer = .porter() // porter wrapping unicode61 (the default)
The porter tokenizer is a wrapper tokenizer which compares English words according to their roots: it matches "database" with "databases", and "frustration" with "frustrated".
It strips diacritics from latin script characters if it wraps unicode61, and does not if it wraps ascii (see the example above).
See [SQLite tokenizers](https://www.sqlite.org/fts5.html#tokenizers) for more information, and [custom FTS5 tokenizers](FTS5Tokenizers.md) in order to add your own tokenizers.
## FTS5 Tokenization
You can tokenize strings when needed:
```swift
let ascii = try db.makeTokenizer(.ascii())
// Tokenize an FTS5 query
for (token, flags) in try ascii.tokenize(query: "SQLite database") {
print(token) // Prints "sqlite" then "database"
}
// Tokenize an FTS5 document
for (token, flags) in try ascii.tokenize(document: "SQLite database") {
print(token) // Prints "sqlite" then "database"
}
```
Some tokenizers may produce a different output when you tokenize a query or a document (see `FTS5_TOKENIZE_QUERY` and `FTS5_TOKENIZE_DOCUMENT` in https://www.sqlite.org/fts5.html#custom_tokenizers). You should generally use `tokenize(query:)` when you intend to tokenize a string in order to compose a [raw search pattern](#fts5pattern).
See the `FTS5_TOKEN_*` flags in https://www.sqlite.org/fts5.html#custom_tokenizers for more information about token flags. In particular, tokenizers that support synonyms may output multiple tokens for a single word, along with the `.colocated` flag.
## FTS5Pattern
**Full-text search in FTS5 tables is performed with search patterns:**
- `database` matches all documents that contain "database"
- `data*` matches all documents that contain a word starting with "data"
- `SQLite database` matches all documents that contain both "SQLite" and "database"
- `SQLite OR database` matches all documents that contain "SQLite" or "database"
- `"SQLite database"` matches all documents that contain the "SQLite database" phrase
**Not all search patterns are valid**: they must follow the [Full-Text Query Syntax](https://www.sqlite.org/fts5.html#full_text_query_syntax).
The FTS5Pattern type helps you validate patterns, and build valid patterns from untrusted strings (such as strings typed by users):
The `Database.makeFTS5Pattern(rawPattern:forTable:)` method validates your raw patterns against the query grammar and the columns of the targeted table, and may throw a [DatabaseError](../README.md#databaseerror):
The FTS5Pattern initializers don't throw. They build a valid pattern from any string, **including strings provided by users of your application**. They let you find documents that match all given words, any given word, or a full phrase, depending on the needs of your application:
```swift
let query = "SQLite database"
// Matches documents that contain "SQLite" or "database"
let pattern = FTS5Pattern(matchingAnyTokenIn: query)
// Matches documents that contain "SQLite" and "database"
let pattern = FTS5Pattern(matchingAllTokensIn: query)
// Matches documents that contain words that start with "SQLite" and words that start with "database"
let pattern = FTS5Pattern(matchingAllPrefixesIn: query)
// Matches documents that contain "SQLite database"
let pattern = FTS5Pattern(matchingPhrase: query)
// Matches documents that start with "SQLite database"
let pattern = FTS5Pattern(matchingPrefixPhrase: query)
```
They return nil when no pattern could be built from the input string:
```swift
let pattern = FTS5Pattern(matchingAnyTokenIn: "") // nil
let pattern = FTS5Pattern(matchingAnyTokenIn: "*") // nil
```
FTS5Pattern instances are regular [values](../README.md#values). You can use them as query [arguments](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/statementarguments):
```swift
let documents = try Document.fetchAll(db,
sql: "SELECT * FROM document WHERE document MATCH ?",
arguments: [pattern])
```
Use them in the [query interface](../README.md#the-query-interface):
```swift
// Search in all columns
let documents = try Document.matching(pattern).fetchAll(db)
// Search in a specific column:
let documents = try Document.filter { $0.content.match(pattern) }.fetchAll(db)
```
## FTS5: Sorting by Relevance
**FTS5 can sort results by relevance** (most to least relevant):
```swift
// SQL
let documents = try Document.fetchAll(db,
sql: "SELECT * FROM document WHERE document MATCH ? ORDER BY rank",
arguments: [pattern])
// Query Interface
let documents = try Document.matching(pattern).order(Column.rank).fetchAll(db)
```
For more information about the ranking algorithm, as well as extra options, read [Sorting by Auxiliary Function Results](https://www.sqlite.org/fts5.html#sorting_by_auxiliary_function_results).
GRDB does not provide any ranking for FTS3 and FTS4. See SQLite's [Search Application Tips](https://www.sqlite.org/fts3.html#appendix_a) if you really need it.
## External Content Full-Text Tables
**An external content table does not store the indexed text.** Instead, it indexes the text stored in another table.
This is very handy when you want to index a table that cannot be declared as a full-text table (because it contains non-textual values, for example). You just have to define an external content full-text table that refers to the regular table.
The two tables must be kept up-to-date, so that the full-text index matches the content of the regular table. This synchronization happens automatically if you use the `synchronize(withTable:)` method in your full-text table definition:
```swift
// A regular table
try db.create(table: "book") { t in
t.column("author", .text)
t.column("title", .text)
t.column("content", .text)
...
}
// A full-text table synchronized with the regular table
try db.create(virtualTable: "book_ft", using: FTS4()) { t in // or FTS5()
t.synchronize(withTable: "book")
t.column("author")
t.column("title")
t.column("content")
}
```
Any content already present in the regular table is indexed, and every insert, update or delete that happens in the regular table is automatically applied to the full-text index.
For more information, see the SQLite documentation about external content tables: [FTS4](https://www.sqlite.org/fts3.html#_external_content_fts4_tables_), [FTS5](https://sqlite.org/fts5.html#external_content_tables).
See also [WWDC Companion](https://github.com/groue/WWDCCompanion), a sample app that uses external content tables to store, display, and let the user search the WWDC sessions.
### Deleting Synchronized Full-Text Tables
Synchronization of full-text tables with their content table happens by means of SQL triggers.
SQLite automatically deletes those triggers when the content (not full-text) table is dropped.
However, those triggers remain after the full-text table has been dropped. Unless they are dropped too, they will prevent future insertions, updates, and deletions in the content table, and the creation of a new full-text table.
To drop those triggers, use the `dropFTS4SynchronizationTriggers` or `dropFTS5SynchronizationTriggers` methods:
```swift
// Create tables
try db.create(table: "book") { t in
...
}
try db.create(virtualTable: "book_ft", using: FTS4()) { t in
> **Warning**: there was a bug in GRDB up to version 2.3.1 included, which created triggers with a wrong name. If it is possible that the full-text table was created by an old version of GRDB, then delete the synchronization triggers **twice**: once with the name of the deleted full-text table, and once with the name of the content table:
> try db.dropFTS4SynchronizationTriggers(forTable: "book") // Support for GRDB <= 2.3.1
> ```
### Querying External Content Full-Text Tables
When you need to perform a full-text search, and the external content table contains all the data you need, you can simply query the full-text table.
But if you need to load columns from the regular table, and also perform a full-text search, then you will need to query both tables at the same time.
That is because SQLite will throw an error when you try to perform a full-text search on a regular table:
```swift
// SQLite error 1: unable to use function MATCH in the requested context
// SELECT * FROM book WHERE book MATCH '...'
let books = Book.matching(pattern).fetchAll(db)
```
The solution is to perform a joined request, using raw SQL:
```swift
let sql = """
SELECT book.*
FROM book
JOIN book_ft
ON book_ft.rowid = book.rowid
AND book_ft MATCH ?
"""
let books = Book.fetchAll(db, sql: sql, arguments: [pattern])
```
## Full-Text Records
**You can define [record](../README.md#records) types around the full-text virtual tables.**
The primary key of those tables is the hidden `rowid` column. If you need to fetch, delete, and update full-text records by primary key, you will have to expose this column to the record type. See [The Database Schema](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databaseschema) for more information.
## Unicode Full-Text Gotchas
The SQLite built-in tokenizers for [FTS3, FTS4](#fts3-and-fts4-tokenizers) and [FTS5](#fts5-tokenizers) are generally unicode-aware, with a few caveats, and limitations.
Generally speaking, matches may fail when content and query don't use the same [unicode normalization](http://unicode.org/reports/tr15/). SQLite actually exhibits inconsistent behavior in this regard.
For example, for "aimé" to match "aimé", they better have the same normalization: the NFC "aim\u{00E9}" form may not match its NFD "aime\u{0301}" equivalent. Most strings that you get from Swift, UIKit and Cocoa use NFC, so be careful with NFD inputs (such as strings from the HFS+ file system, or strings that you can't trust like network inputs). Use [String.precomposedStringWithCanonicalMapping](https://developer.apple.com/documentation/foundation/nsstring/1412645-precomposedstringwithcanonicalma) to turn a string into NFC.
Besides, if you want "fi" to match the ligature "fi" (U+FB01), then you need to normalize your indexed contents and inputs to NFKC or NFKD. Use [String.precomposedStringWithCompatibilityMapping](https://developer.apple.com/documentation/foundation/nsstring/1412625-precomposedstringwithcompatibili) to turn a string into NFKC.
Unicode normalization is not the end of the story, because it won't help "Encyclopaedia" match "Encyclopædia", "Mueller", "Müller", "Grossmann", "Großmann", or "Diyarbakır", "DIYARBAKIR". The [String.applyingTransform](https://developer.apple.com/documentation/foundation/nsstring/1407787-applyingtransform) method can help.
GRDB lets you write [custom FTS5 tokenizers](FTS5Tokenizers.md) that can transparently deal with all these issues. For FTS3 and FTS4, you'll need to pre-process your strings before injecting them in the full-text engine.
GRDB 3 comes with new features, but also a few breaking changes, and a set of updated good practices. This guide aims at helping you upgrading your applications.
**For all users**
- [Swift 4.1 Required]
- [iOS 8 Sunsetting]
- [Database Schema Recommendations]
- [Record Protocols Renaming]
- [Columns Definition]
**By topic**
- [If You Use Database Queues]
- [If You Use Database Pools]
- [If You Use Database Snapshots]
- [If You Use Record Types]
- [If You Use Custom Requests]
- [If You Use RxGRDB]
- [Notable Documentation Updates]
## Swift 4.1 Required
GRDB 3 uses [conditional conformances], introduced in Swift 4.1. It can only be built on Xcode 9.3+.
## iOS 8 Sunsetting
GRDB 3 is only tested on iOS 9+, due to a limitation in Xcode 9.3. Code that targets older versions of SQLite and iOS is still there, but is not supported.
## Database Schema Recommendations
GRDB 2 was totally schema-agnostic, and would gladly accept any database.
GRDB 3 still accepts any database, but brings two schema recommendations:
- :bulb: Integer primary keys should be auto-incremented, in order to avoid any row id to be reused.
When ids can be reused, your app and [database observation tools] may think that a row was updated, when it was actually deleted, then replaced. Depending on your application needs, this may be OK. Or not.
GRDB 3 thus comes with a new good practice: use the `autoIncrementedPrimaryKey` method when you create a database table with an integer primary key:
- :bulb: Database table names should be singular, and camel-cased. Make them look like Swift identifiers: `place`, `country`, `postalAddress`, 'httpRequest'.
This will help you using the new [Associations] feature when you need it. Database table names that follow another naming convention are totally OK, but you will need to perform extra configuration.
This convention is applied by the default implementation of the `TableRecord.databaseTableName`: see [If You Use Record Types] below.
Since you are reading this guide, your application has already defined its database schema. You can migrate it in order to apply the new recommendations, if needed. Below is a sample code that uses [DatabaseMigrator], the recommended tool for managing your database schema:
After upgrading, build your project: the compiler will guide you through the renaming by the way of fixits.
## Columns Definition
GRDB 2 has you define columns of the query interface with the Column type:
```swift
// GRDB 2
let nameColumn = Column("name")
let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
```
A recommended practice was to define enum namespaces in record types:
```swift
// GRDB 2
struct Player: RowConvertible, TableMapping {
enum Columns {
static let id = Column("id")
static let name = Column("name")
static let score = Column("score")
}
init(row: Row) {
id = row[Columns.id]
name = row[Columns.name]
score = row[Columns.score]
}
}
```
In GRDB 3, `Column` is still there, but a new `ColumnExpression` protocol has been introduced in order to streamline column enums:
```swift
// GRDB 3
struct Player: FetchableRecord, TableRecord {
enum Columns: String, ColumnExpression {
case id, name, score
}
init(row: Row) {
id = row[Columns.id]
name = row[Columns.name]
score = row[Columns.score]
}
}
```
GRDB can apply additional optimizations on expressions that adopt ColumnExpression, so conform to this protocol when you define a custom column type:
```swift
struct TypedColumn: ColumnExpression {
var name: String
var sqlType: String
}
let nameColumn = TypedColumn(name: "name", sqlType: "VARCHAR")
let arthur = try Player.filter(nameColumn == "Arthur").fetchOne(db)
```
## If You Use Database Queues
With GRDB 2, you used to access the database through the `inDatabase` or `inTransaction` [DatabaseQueue] methods:
```swift
// GRDB 2
let players = try dbQueue.inDatabase { db in
try Player.fetchAll(db)
}
try dbQueue.inDatabase { db in
try player.updateChanges(db)
}
var balance: Amount! = nil
try dbQueue.inTransaction { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
balance = try sourceAccount.fetchBalance(db)
return .commit
}
```
The code above still runs, unchanged, in GRDB 3.
Yet it is now recommended that you use the `read` and `write` methods instead:
```swift
// GRDB 3
let players = try dbQueue.read { db in
try Player.fetchAll(db)
}
try dbQueue.write { db in
try player.updateChanges(db)
}
let balance = try dbQueue.write { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
return try sourceAccount.fetchBalance(db)
}
```
The purpose of the new `read` and `write` methods is to soothe the "transaction mental load" of previous versions of GRDB, a legacy of the [FMDB] heritage. All developers can *forget* to open transactions, with the unfortunate consequence that the database may end up containing inconsistent values. Experienced developers may *wonder* whether they should open transactions or not, even when this doesn't matter a lot.
With GRDB 3, use `read` when you need to read values. It's impossible to write within a `read` block, which means that you can be sure that no unwanted side effect can happen.
When you need to write, use `write`: your database changes are automatically wrapped in a transaction, with the guarantee that all changes are written to disk, or, should any error happen, none at all.
Of course, precise transaction handling sometimes matter. Check the updated [Transactions and Savepoints] chapter.
## If You Use Database Pools
With GRDB 2, you used to access the database through the `read`, `write` or `writeInTransaction` [DatabasePool] methods:
```swift
// GRDB 2
let players = try dbPool.read { db in
try Player.fetchAll(db)
}
try dbPool.write { db in
try player.updateChanges(db)
}
var balance: Amount! = nil
try dbPool.writeInTransaction { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
balance = try sourceAccount.fetchBalance(db)
return .commit
}
```
In GRDB 3, the `write` method has changed: it now automatically wraps your database changes in a transaction, which means that the last block can be rewritten as below:
```swift
// GRDB 3
let balance = try dbPool.write { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
return try sourceAccount.fetchBalance(db)
}
```
Side effect: you can no longer open explicit transactions inside a `write` block:
// cannot start a transaction within a transaction
try dbPool.write { db in
try db.inTransaction { ... }
}
```
When precise transaction handling is needed, check the updated [Transactions and Savepoints] chapter.
The purpose of this change is to prevent an easy misuse of database pools in previous GRDB versions. Unless writes were wrapped inside an explicit transactions, concurrent reads could see an inconsistent state of the database:
```swift
// GRDB 2: unsafe
// GRDB 3: safe
try dbPool.write { db in
try Credit(destinationAccout, amount).insert(db)
try Debit(sourceAccount, amount).insert(db)
}
```
Since `write` now wraps your changes in a transaction, you have the guarantee that concurrent reads can't see them until they are all written to disk.
## If You Use Database Snapshots
With GRDB 2, you used to create [database snapshots] with the `makeSnaphot` [DatabasePool] method. For example:
```swift
// GRDB 2
let snapshot: DatabaseSnapshot = try dbPool.write { db in
try Player.deleteAll()
return dbPool.makeSnapshot()
}
// Guaranteed to be zero
let count = try snapshot.read { db in
try Player.fetchCount(db)
}
```
GRDB 3 will crash the above code on the `makeSnapshot()` line, with a fatal error: "makeSnapshot() must not be called from inside a transaction."
To avoid this error, you will need [precise transaction handling]:
```swift
// GRDB 3
let snapshot: DatabaseSnapshot = try dbPool.writeWithoutTransaction { db in
try Player.deleteAll()
return dbPool.makeSnapshot()
}
```
## If You Use Record Types
Record types that adopt the former TableMapping protocol, renamed TableRecord, used to declare their table name:
```swift
// GRDB 2
struct Place: TableMapping {
static let databaseTableName = "place"
}
print(Place.databaseTableName) // print "place"
```
With GRDB 3, the `databaseTableName` property gets a default implementation:
```swift
// GRDB 3
struct Place: TableRecord { }
print(Place.databaseTableName) // print "place"
```
That default name follows the [Database Schema Recommendations]: it is singular, camel-cased, and looks like a Swift identifier:
- Place: `place`
- Country: `country`
- PostalAddress: `postalAddress`
- HTTPRequest: `httpRequest`
- TOEFL: `toefl`
When you subclass the Record class, the Swift compiler won't let you profit from this default name: you have to keep on providing an explicit table name:
```swift
// GRDB 2 and GRDB 3
class Place: Record {
override var databaseTableName: String {
return "place"
}
}
```
## If You Use Custom Requests
[Custom requests] let you escape the limitations of the [query interface], when it can not generate the requests you need.
let players = try Player.filter(color: .red).fetchAll(db)
```
See the updated [Custom Requests](../README.md#custom-requests) chapter for more information.
## If You Use RxGRDB
Some RxGRDB APIs have slighly changed. Did you track multiple requests at the same time with "fetch tokens"?
```swift
// GRDB 2
dbQueue.rx
.fetchTokens(in: [request, ...])
.mapFetch { db in try fetchResult(db) }
.subscribe(...)
```
Now you'll write instead:
```swift
// GRDB 3
dbQueue.rx
.fetch(from: [request, ...]) { db in try fetchResult(db) }
.subscribe(...)
```
It's just a syntactic change, without any impact on the runtime.
RxGRDB for GRDB 3 also introduces a new protocol, [DatabaseRegionConvertible], that allows a better encapsulation of complex requests, and a streamlined observable definition.
For example:
```swift
// GRDB 2: Track a team and its players
let teamId = 1
let teamRequest = Team.filter(key: teamId)
let playersRequest = Player.filter(teamId: teamId)
dbQueue.rx
.fetchTokens(in: [teamRequest, playersRequest])
.mapFetch { db -> TeamInfo? in
guard let team = try teamRequest.fetchOne(db) else {
If you have time, you may dig deeper in GRDB 3 with those updated documentation chapter:
- [Database Queues](../README.md#database-queues): focus on the new `read` and `write` methods.
- [Transactions and Savepoints](../README.md#transactions-and-savepoints): the chapter has been rewritten in order to introduce transactions as a power-user feature.
- [ScopeAdapter](../README.md#scopeadapter): do you use row adapters? If so, have a look.
- [Examples of Record Definitions](../README.md#examples-of-record-definitions): this new chapter provides a handy reference of the three main ways to define record types (Codable, plain struct, Record subclass).
- [SQL Operators](../README.md#sql-operators): the chapter introduces the new `joined(operator:)` method that lets you join a chain of expressions with `AND` or `OR` without nesting: `[cond1, cond2, ...].joined(operator: .and)`.
- [Custom Requests](../README.md#custom-requests): the old `Request` and `TypedRequest` protocols have been replaced with `FetchRequest`. If you want to know more about custom requests, check this chapter.
- [Migrations](../README.md#migrations): learn how to check if a migration has been applied (very useful for migration tests).
If you haven't made it yet, upgrade to the [latest GRDB 4 release](https://github.com/groue/GRDB.swift/tags) first, and fix any deprecation warning prior to the GRDB 5 upgrade.
GRDB 5 ships with fix-its that will suggest simple syntactic changes, and won't require you to think much.
Your attention will be needed, though, in the area of database observation.
## New requirements
GRDB requirements have been bumped:
- **Swift 5.3+** (was Swift 4.2+)
- **Xcode 12.0+** (was Xcode 10.0+)
- **iOS 11.0+** (was iOS 9.0+)
- **macOS 10.10+** (was macOS 10.9+)
- tvOS 9.0+ (unchanged)
- watchOS 2.0+ (unchanged)
## Database Configuration
The way to configure a database relies much more on the `Configuration.prepareDatabase(_:)` method:
[ValueObservation] is the database observation tool that tracks changes in database values. It has changed quite a bit in GRDB 5.
Those changes make the vanilla GRDB, its [Combine publishers], and [RxGRDB] offer a common API, and a common behavior. This greatly helps choose or switch your preferred database observation technique. In previous versions of GRDB, the three companion libraries used to have subtle differences that were just opportunities for bugs.
In the end, this migration step might require some work. But it's for the benefit of all!
Finally, ValueObservation used to let applications define custom "reducers" based on a protocol named ValueReducer, which was removed in GRDB 5. See the [#731](https://github.com/groue/GRDB.swift/pull/731) conversation for a solution towards a replacement.
The `start` method which starts observing the database has changed as well.
```swift
//Startobservingthedatabase
letcancellable=observation.start(
in:dbQueue,
onError:{errorin...},
onChange:{valueinprint("fresh value: \(value)")})
```
1. The result of the `start` method is now a DatabaseCancellable which allows you to explicitly stop an observation:
```swift
// BEFORE: GRDB 4
let observer: TransactionObserver?
observer = observation.start(...)
observer = nil // Stop the observation
// NEW: GRDB 5
let cancellable: DatabaseCancellable
cancellable = observation.start(...)
cancellable.cancel() // Stop the observation
```
The returned DatabaseCancellable cancels itself when it gets deinitialized.
2. The `onError` handler of the `start` method is now mandatory:
```swift
// BEFORE: GRDB 4
do {
try observation.start(in: dbQueue) { value in
print("fresh value: \(value)")
}
} catch { ... }
// NEW: GRDB 5
observation.start(
in: dbQueue,
onError: { error in ... },
onChange: { value in print("fresh value: \(value)") })
```
### Runtime Behavior of ValueObservation
**The behavior of ValueObservation has changed**.
The changes can have quite an impact on your application. We'll describe them below, as well as the strategies to restore the previous behavior when needed.
1. ValueObservation used to notify its initial value *immediately* when the observation starts. Now, it notifies fresh values on the main thread, *asynchronously*, by default.
This means that the parts of your application that rely on this immediate value to, say, set up their user interface, have to be modified. Otherwise, they may suffer from a brief flash of missing data, during the short amount of time between the beginning of the observation, and the asynchronous delivery of the initial value.
To get an immediate, synchronous, delivery of the initial value, insert a `scheduling: .immediate` argument in the `start` method:
```swift
let observation = ValueObservation.tracking(Player.fetchAll)
let cancellable = observation.start(
in: dbQueue,
// Opt in for immediate notification of the initial value
scheduling: .immediate,
onError: { error in ... },
onChange: { [weak self] (players: [Player]) in
guard let self else { return }
self.updateView(players)
})
// <- Here the view has already been updated.
```
Note that the `.immediate` scheduling requires that the observation starts from the main thread. A fatal error is raised otherwise.
<details>
<summary>Combine impact</summary>
```swift
let observation = ValueObservation.tracking(Player.fetchAll)
let cancellable = observation
.publisher(
in: dbQueue,
// Opt in for immediate notification of the initial value
scheduling: .immediate)
.sink(...)
```
</details>
<details>
<summary>RxGRDB impact</summary>
```swift
let observation = ValueObservation.tracking(Player.fetchAll)
let disposable = observation
.rx.observe(
in: dbQueue,
// Opt in for immediate notification of the initial value
scheduling: .immediate)
.subscribe(...)
```
</details>
2. ValueObservation used to notify one fresh value for each and every database transaction that had an impact on the tracked value. Now, it may coalesce notifications. If your application relies on exactly one notification per transaction, use [DatabaseRegionObservation] instead.
3. Some value observations used to automatically remove duplicate values. This is no longer automatic. If your application relies on distinct consecutive values, use the [removeDuplicates] operator.
4. ValueObservation used to prevent a database connection (DatabaseQueue or DatabasePool) from closing. Now an observation just stops emitting any fresh value when the database connection closes.
5. ValueObservation used to be able to restart notifying fresh values after it has notified an error. Now an error marks the end of the observation.
6. ValueObservation used to have a `scheduling` property, which has been removed.
You can remove the explicit request to dispatch fresh values asynchronously on the main dispatch queue, because it is now the default behavior:
The GRDB 4 `startImmediately` parameter is no longer supported: ValueObservation now always emits an initial value, without waiting for changes. It is up to your application to ignore this initial value if it wants to.
### Removed ValueObservation Methods
1. ValueObservation used to have a `compactMap` method. This method has been removed without any replacement.
If your application uses Combine publishers or RxGRDB, then use the `compactMap` method from Combine or RxSwift instead.
2. ValueObservation used to have a `combine` method. This method has been removed without any replacement.
In your application, replace combined observations with a single observation:
```swift
struct HallOfFame {
var totalPlayerCount: Int
var bestPlayers: [Player]
}
// BEFORE: GRDB 4
let totalPlayerCountObservation = ValueObservation.tracking(Player.fetchCount)
let bestPlayersObservation = ValueObservation.tracking(Player
let observation = ValueObservation.tracking { db -> HallOfFame in
let totalPlayerCount = try Player.fetchCount(db)
let bestPlayers = try Player
.order(Column("score").desc)
.limit(10)
.fetchAll(db)
return HallOfFame(
totalPlayerCount: totalPlayerCount,
bestPlayers: bestPlayers)
}
```
As in previous versions of GRDB, do not use the `combineLatest` operators of Combine or RxSwift in order to combine several ValueObservation instances. You would lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
## Combine Integration
GRDB 4 had a companion library named GRDBCombine. Combine support is now embedded right into GRDB 5, and you have to remove any dependency on GRDBCombine.
GRDBCombine used to define a `fetchOnSubscription()` method of the ValueObservation subscriber. It has been removed. Replace it with `scheduling: .immediate` for the same effect (an initial value is notified immediately, synchronously, when the publisher is subscribed):
```swift
// BEFORE: GRDB 4 + GRDBCombine
let observation = ValueObservation.tracking { db in ... }
let publisher = observation
.publisher(in: dbQueue)
.fetchOnSubscription()
// NEW: GRDB 5
let observation = ValueObservation.tracking { db in ... }
let publisher = observation
.publisher(in: dbQueue, scheduling: .immediate)
```
## Other Changes
1. The `Configuration.trace` property has been removed. You now use the `Database.trace(options:_:)` method instead:
```swift
// BEFORE: GRDB 4
var config = Configuration()
config.trace = { print($0) }
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
// NEW: GRDB 5
var config = Configuration()
config.prepareDatabase { db in
db.trace { print($0) }
}
let dbQueue = try DatabaseQueue(path: dbPath, configuration: config)
```
2. [Batch updates] used to rely on the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
> :question: This change avoids conflicts with other libraries that define the same operator.
3. [SQL Interpolation] no longer wraps subqueries in parentheses:
```swift
// BEFORE: GRDB 4
let maximumScore: SQLRequest<Int> = "SELECT MAX(score) FROM player"
let bestPlayers: SQLRequest<Player> = "SELECT * FROM player WHERE score = \(maximumScore)"
// NEW: GRDB 5
let maximumScore: SQLRequest<Int> = "SELECT MAX(score) FROM player"
let bestPlayers: SQLRequest<Player> = "SELECT * FROM player WHERE score = (\(maximumScore))"
// extra parentheses required: ^ ^
```
> :question: This change makes it possible to concatenate subqueries with the UNION operator.
4. In order to extract the raw SQL string from an [SQL literal], you now need a database connection:
```swift
// BEFORE: GRDB 4
let query: SQLLiteral = "UPDATE player SET name = \(name) WHERE id = \(id)"
print(query.sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(query.arguments) // prints ["O'Brien", 42]
// NEW: GRDB 5
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try dbQueue.read { db in
try query.build(db)
}
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
```
5. In order to extract the raw SQL string from a request ([SQLRequest] or [QueryInterfaceRequest]), you now need to call the `makePreparedRequest()` method:
```swift
// BEFORE: GRDB 4
try dbQueue.read { db in
let request = Player.filter(Column("name") == "O'Brien")
let sqlRequest = try SQLRequest(db, request: request)
print(sqlRequest.sql) // "SELECT * FROM player WHERE name = ?"
print(sqlRequest.arguments) // ["O'Brien"]
}
// NEW: GRDB 5
try dbQueue.read { db in
let request = Player.filter(Column("name") == "O'Brien")
let statement = try request.makePreparedRequest(db, forSingleResult: false).statement
print(statement.sql) // "SELECT * FROM player WHERE name = ?"
print(statement.arguments) // ["O'Brien"]
}
```
6. The `TableRecord.selectionSQL()` method is no longer available. When you need to embed the columns selected by a record type in an SQL request, you now have to use [SQL Interpolation]:
```swift
// BEFORE: GRDB 4
let sql = "SELECT \(Player.selectionSQL()) FROM player"
let players = try Player.fetchAll(db, sql: sql)
// NEW: GRDB 5
let request: SQLRequest<Player> = "SELECT \(columnsOf: Player.self) FROM player"
let players = try request.fetchAll(db)
```
7. [Custom SQL functions] are now [callable values](https://github.com/apple/swift-evolution/blob/master/proposals/0253-callable.md):
```swift
// BEFORE: GRDB 4
Player.select(myFunction.call(Column("name")))
// NEW: GRDB 5
Player.select(myFunction(Column("name")))
```
8. Defining custom `FetchRequest` types is no longer supported.
Refactor your app around [SQLRequest] and [QueryInterfaceRequest], which are supposed to fully address your needs.
9. The module name for [custom SQLite builds](CustomSQLiteBuilds.md) is now the plain `GRDB`:
```swift
// BEFORE: GRDB 4
import GRDBCustomSQLite
// NEW: GRDB 5
import GRDB
```
10. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You no longer need to import the underlying SQLite library:
```swift
// BEFORE: GRDB 4
import CSQLite // When GRDB is included with the Swift Package Manager
import SQLCipher // When GRDB is linked to SQLCipher
import SQLite3 // When GRDB is linked to System SQLite
let sqliteVersion = String(cString: sqlite3_libversion())
// NEW: GRDB 5
import GRDB
let sqliteVersion = String(cString: sqlite3_libversion())
```
11. `FetchedRecordsController` was removed from GRDB 5. The [Database Observation] chapter describes the other ways to observe the database.
12. Defining custom `RowAdapter` types is no longer supported. A new [RenameColumnAdapter](../README.md#renamecolumnadapter) adapter makes it possible to process column names.
13. Many types and methods that support the query builder used to be publicly exposed and flagged as experimental. They are now private, or renamed with an underscore prefix, which means they are not for public use.
14. Explicit boolean tests `expression == true` and `expression == false` generate different SQL:
```swift
// GRDB 4: SELECT * FROM player WHERE isActive
// GRDB 5: SELECT * FROM player WHERE isActive = 1
Player.filter(Column("isActive") == true)
// GRDB 4: SELECT * FROM player WHERE NOT isActive
// GRDB 5: SELECT * FROM player WHERE isActive = 0
Player.filter(Column("isActive") == false)
// GRDB 4 & 5: SELECT * FROM player WHERE isActive
Player.filter(Column("isActive"))
// GRDB 4 & 5: SELECT * FROM player WHERE NOT isActive
Player.filter(!Column("isActive"))
```
This change is innocuous for database boolean values that are `0`, `1`, or `NULL`. However, it is a breaking change for all other database values.
If you haven't made it yet, upgrade to the [latest GRDB 5 release](https://github.com/groue/GRDB.swift/tags) first, and fix any deprecation warning prior to the GRDB 6 upgrade.
You can then upgrade to GRDB 6. Due to the breaking changes, it is possible that your application code no longer compiles. Follow the fix-its that suggest simple syntactic changes. Other modifications that you need to apply are described below.
## New requirements
GRDB requirements have been bumped:
- **Swift 5.7+** (was Swift 5.3+)
- **Xcode 14.0+** (was Xcode 12.0+)
- iOS 11.0+ (unchanged)
- **macOS 10.13+** (was macOS 10.10+)
- **tvOS 11.0+** (was tvOS 9.0+)
- **watchOS 4.0+** (was watchOS 2.0+)
- **SQLite 3.19.3+** (was SQLite 3.8.5+)
## Primary Associated Types
Request protocols now come with a primary associated type, enabled by [SE-0346](https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md). This is a great opportunity to simplify your extensions:
```diff
-extension DerivableRequest where RowDecoder == Book {
+extension DerivableRequest<Book> {
/// Order books by title, in a localized case-insensitive fashion
Your extensions to `QueryInterfaceRequest` can be streamlined as well, thanks to [SE-0361](https://github.com/apple/swift-evolution/blob/main/proposals/0361-bound-generic-extensions.md):
```diff
-extension QueryInterfaceRequest where RowDecoder == Player {
+extension QueryInterfaceRequest<Player> {
func selectID() -> QueryInterfaceRequest<Int64> {
selectPrimaryKey()
}
}
```
The `Cursor` protocol has also gained a primary associated type (the type of its elements).
## Record Changes
The record protocols have been refactored. We tried to keep the amount of modifications to your existing code as small as possible, but some changes could not be avoided.
- **The `FetchableRecord.init(row:)` initializer can now throw errors.**
```diff
-let player = Player(row: row)
+let player = try Player(row: row)
```
Decodable records that derive their `FetchableRecord` implementation from the standard `Decodable` protocol now throw errors when they find unexpected database values (they used to crash in GRDB 5).
If you subclass the `Record` type, you have to update your override of `init(row:)`:
```diff
class Player: Record {
- required init(row: Row) {
+ required init(row: Row) throws {
self.id = row["id"]
self.name = row["name"]
- super.init(row: row)
+ try super.init(row: row)
}
}
```
In record types that do not derive their `FetchableRecord.init(row:)` implementation from the standard `Decodable` protocol, you are responsible for throwing decoding errors, as in the sample code below:
<details>
<summary>Handling untrusted input</summary>
For example:
```swift
struct LogEntry: FetchableRecord {
var date: Date
init(row: Row) throws {
let dbValue: DatabaseValue = row["date"]
if dbValue.isNull {
// Handle NULL
throw ...
} else if let date = Date.fromDatabaseValue(dbValue) {
self.date = date
} else {
// Handle invalid date
throw ...
}
}
}
```
</details>
- **The `EncodableRecord.encode(to:)` method can now throw errors.**
Encodable records that derive their `EncodableRecord` implementation from the standard `Encodable` protocol now throw errors when they can't be encoded into database values (they used to crash in GRDB 5).
If you subclass the `Record` type, you have to update your override of `encode(to:)`:
- **PersistableRecord types now customize persistence methods with "persistence callbacks"**.
It is no longer possible to override persistence methods such as `insert` or `update`. Customizing the persistence methods is now possible with callbacks such as `willSave`, `willInsert`, or `didDelete` (see [persistence callbacks] for the full list of callbacks).
**You have to remove the methods below from your own code base**:
```swift
// GRDB 6: remove those methods from your code
func insert(_ db: Database) throws
func didInsert(with rowID: Int64, for column: String?)
- `insert(_:)`: customization is now made with [persistence callbacks].
- `didInsert(with:for:)`: this method was renamed `didInsert(_:)` (see previous bullet point).
- `update(_:columns:)`: customization is now made with [persistence callbacks].
- `save(_:)`: customization is now made with [persistence callbacks].
- `delete(_:)`: customization is now made with [persistence callbacks].
- `exists(_:)`: this method is no longer customizable.
To help you update your applications with persistence callbacks, let's look at two examples.
First, check the updated [Single-Row Tables](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/singlerowtables) guide, if your application defines a "singleton record".
Next, let's consider a record that performs some validation before insertion and updates. In GRDB 5, this would look like:
With GRDB 6, record validation can be implemented with the `willSave` callback:
```swift
// GRDB 6
struct Link: PersistableRecord {
var url: URL
func willSave(_ db: Database) throws {
if url.host == nil {
throw ValidationError("url must be absolute.")
}
}
}
try link.insert(db) // Calls the willSave callback
try link.update(db) // Calls the willSave callback
try link.save(db) // Calls the willSave callback
try link.upsert(db) // Calls the willSave callback
```
If you subclass the `Record` class, you have to call `super` at some point in your implementation:
```swift
// GRDB 6
class Link: Record {
var url: URL
override func willSave(_ db: Database) throws {
try super.willSave(db)
if url.host == nil {
throw ValidationError("url must be absolute.")
}
}
}
```
- **Handling of the `IGNORE` conflict policy**
The SQLite [IGNORE](https://www.sqlite.org/lang_conflict.html) conflict policy has SQLite skip insertions and updates that violate a schema constraint, without reporting any error. You can skip this paragraph if you do not use this policy.
GRDB 6 has slightly changed the handling of the `IGNORE` policy.
The `didInsert` callback is now always called on `INSERT OR IGNORE` insertions. In GRDB 5, `didInsert` was not called for record types that specify the `.ignore` conflict policy on inserts:
```swift
// Given a record with ignore conflict policy for inserts...
struct Player: TableRecord, FetchableRecord {
static let persistenceConflictPolicy = PersistenceConflictPolicy(insert: .ignore)
}
// GRDB 5: Does not call didInsert
// GRDB 6: Calls didInsert
try player.insert(db)
```
Since `INSERT OR IGNORE` may silently fail, the `didInsert` method will be called with some random rowid in case of failed insert. You can detect failed insertions with the new method `insertAndFetch`:
```swift
// How to detect failed `INSERT OR IGNORE`:
// INSERT OR IGNORE INTO player ... RETURNING *
if let insertedPlayer = try player.insertAndFetch(db) {
// Successful insertion
} else {
// Ignored failure
}
```
## Other Changes
- The initializer of in-memory databases can now throw errors:
```diff
-let dbQueue = DatabaseQueue()
+let dbQueue = try DatabaseQueue()
```
- The `selectID()` method is removed. You can provide your own implementation, based on the new `selectPrimaryKey(as:)` method:
```swift
extension QueryInterfaceRequest<Player> {
func selectID() -> QueryInterfaceRequest<Int64> {
selectPrimaryKey()
}
}
```
- `Cursor.isEmpty` is now a throwing property, instead of a method:
```diff
-if try cursor.isEmpty() { ... }
+if try cursor.isEmpty { ... }
```
- The `Record.copy()` method was removed, without replacement.
- The `DerivableRequest.limit(_:offset:)` method was removed, without replacement.
You can still limit `QueryInterfaceRequest`, but associations can no longer be limited:
```swift
// Still OK: a limited request of authors
let request = Author.limit(10)
// Still OK: a limited request of books
let request = author.request(for: Author.books).limit(10)
// No longer possible: including a limited association
let request = Author.including(all: Author.books.limit(10))
```
- `DatabaseRegionObservation.start(in:onError:onChange:)` now returns a cancellable.
```swift
let observation = DatabaseRegionObservation.tracking(Player.all())
// GRDB 5
do {
let observer = try observation.start(in: dbQueue) { db in
print("Players were modified")
}
} catch {
// handle error
}
// GRDB 6
let cancellable = observation.start(
in: dbQueue,
onError: { error in /* handle error */ },
onChange: { db in
print("Players were modified")
})
```
The `DatabaseRegionObservation.extent` property was removed. You now control the duration of the observation with the cancellable returned from the `start` method.
- Database cursors no longer have a `statement` property. When you want information about the database statement used by a cursor, use dedicated cursor properties. For example:
```diff
-let sql = cursor.statement.sql
-let columns = cursor.statement.columnNames
+let sql = cursor.sql
+let columns = cursor.columnNames
```
- The transaction hook `Database.afterNextTransactionCommit(_:)` was renamed `Database.afterNextTransaction(onCommit:onRollback:)`, and is now able to report rollbacks as well as commits.
```diff
-db.afterNextTransactionCommit { db in
+db.afterNextTransaction { db in
print("Successful commit")
}
```
- If your application directly embeds the `GRDB.xcodeproj` or `GRDBCustom.xcodeproj` project, then you have to update your dependencies. Those projects now define cross-platform targets, and you must perform the following actions:
- In the **Target Dependencies** section of the **Build Phases** tab of your **application targets**, replace the GRDB target with `GRDB` or `GRDBCustom`.
- In the **Embedded Binaries** section of the **General** tab of your **application target**, replace the GRDB framework with `GRDB.framework` or `GRDBCustom.framework`.
- [Associations to record types named Bias, Focus, Gas, and Lens](#associations-to-record-types-named-bias-focus-gas-and-lens)
- [ValueObservation and the Main Actor](#valueobservation-and-the-main-actor)
- [Access to SQLite C functions](#access-to-sqlite-c-functions)
- [The Record Base Class is Discouraged](#the-record-base-class-is-discouraged)
- [Other Changes](#other-changes)
## Preparing the Migration to GRDB 7
Before upgrading, ensure you are using the [latest GRDB 6 release](https://github.com/groue/GRDB.swift/tags) and address any deprecation warnings. Once this is done, proceed with upgrading to GRDB 7. Due to breaking changes, your application may no longer compile. Follow the fix-it suggestions for simple syntax updates, and review the specific modifications described below.
## Recommendations Regarding Swift Concurrency
GRDB 7 requires Xcode 16+ and a Swift 6 compiler.
Depending on the language mode and level of concurrency checking used by your application, you may see warnings or errors. See [Migrating to Swift 6] on swift.org for more information about Swift 6. See [Swift Concurrency and GRDB] for GRDB-focused advice.
In GRDB 6, asynchronous database accesses such as `try await read { ... }` or `try await write { ... }` complete even if the wrapper Task is cancelled.
In GRDB 7, asynchronous database accesses respect Task cancellation. If a Task is cancelled, reads and writes throw a `CancellationError`, pending transactions are rolled back, and the database is not modified. The only SQL statement that can execute in a cancelled database access is `ROLLBACK`.
The effect of this change on your application depends on how it uses tasks. For example, take care of database jobs initiated from the [`task`](https://developer.apple.com/documentation/swiftui/view/task(priority:_:)) SwiftUI modifier.
If you want an asynchronous database access to always complete, regardless of Task cancellation, wrap it in an unstructured Task:
```swift
//CreateanewTaskinordertoignore
//cancellationofthecurrenttask,and
//makesuredatabasechangesarealways
//committedtodisk.
lettask=Task{
tryawaitwriter.write{...}
}
//Ifneeded,waitforthedatabasejobtocomplete:
tryawaittask.value
```
Other asynchronous database accesses, such as methods accepting a completion block (`asyncRead`, etc.), Combine publishers, RxSwift observables, do not handle cancellation and will proceed to completion by default.
## Associations to record types named Bias, Focus, Gas, and Lens
GRDB 7 has fixed its singularization and pluralization rules for database tables named "bias", "focus", "gas", and "lens".
If your application defines associations to those tables, you can now rely on proper inflections (pluralization and singularization).
With GRDB 7, you can remove custom association keys:
If your application was not specifying custom association keys in order to fix the wrong inflections, then it may define types that will no longer decode their properties as intended:
```swift
//WorksinGRDB6,breaksinGRDB7
structCameraWithLenses:Decodable,FetchableRecord{
varcamera:Camera
varlens:[Lens]//<-incorrectpluralization
}
letresults=Camera
.including(all:Camera.lenses)
.asRequest(of:CameraWithLenses.self)
.fetchAll(db)
```
There are two possible solutions. One is to rename properties, the other is to keep on using the wrong inflection (it's your call):
Some applications specify a default transaction kind, which was previously recommended in the [Sharing a Database] guide:
```swift
//GRDB6
varconfig=Configuration()
config.defaultTransactionKind=.immediate
```
In GRDB 7, `Configuration` no longer has a `defaultTransactionKind` property, because transactions are automatically managed. Reads use DEFERRED transactions, and writes use IMMEDIATE transactions.
You can still specify a transaction kind explicitly when necessary. See [Transaction Kinds] for details.
## ValueObservation and the Main Actor
In GRDB 7, `ValueObservation` favors the main actor, because it is frequently used to automatically update database values on screen.
By default, its [`start`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/start(in:scheduling:onerror:onchange:)) method must be called on the main actor, and its notification callbacks run on the main actor as well.
It is not necessary to call `MainActor.assumeIsolated` in `ValueObservation` callbacks:
In GRDB 6, the underlying C SQLite library is implicitly available:
```swift
//GRDB6
importGRDB
letsqliteVersion=sqlite3_libversion_number()
```
In GRDB 7, you may need an additional import, depending on how GRDB is integrated:
- If your app uses the GRDB Swift Package Manager (SPM) package:
```swift
import SQLite3
let sqliteVersion = sqlite3_libversion_number()
```
The GRDB 6 SPM package included a product named "CSQLite." In GRDB 7, this product has been renamed "GRDBSQLite." Update your dependencies accordingly. It is unclear at the time of writing whether some projects can remove this dependency.
- If your app uses SQLCipher:
```swift
import SQLCipher
let sqliteVersion = sqlite3_libversion_number()
```
- In other cases, no additional import is needed.
## The Record Base Class is Discouraged
Subclassing the [Record] class is **discouraged** in GRDB 7. Present in GRDB 1.0, in 2017, it has served its purpose.
It is not recommended to define any new type that subclasses `Record`.
It is recommended to refactor `Record` subclasses into Swift structs, before you enable the strict concurrency checking or the Swift 6 language mode. See [Migrating to Swift 6] for more information about Swift 6 language modes.
For example:
```swift
// GRDB 6
class Player: Record {
var id: UUID
var name: String
var score: Int
override class var databaseTableName: String { "player" }
Do not miss [Swift Concurrency and GRDB], for more recommendations regarding non-Sendable record types in GRDB.
## Other Changes
- `DatabasePool.concurrentRead` has been removed. Use [`asyncConcurrentRead`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasepool/asyncconcurrentread(_:)) instead.
- The `PersistenceContainer` subscript no longer guarantees that the value returned is the same as what was previously set. It only guarantees that both values are encoded identically in the database.
- The async sequence returned by [`ValueObservation.values`](https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/valueobservation/values(in:scheduling:bufferingpolicy:)) now iterates on the cooperative thread pool by default. Use .mainActor as the scheduler if you need the previous behavior.
[Migrating to Swift 6]: https://www.swift.org/migration/documentation/migrationguide
[Sharing a Database]: https://swiftpackageindex.com/groue/GRDB.swift/documentation/grdb/databasesharing
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 simply library application that lets the user crawl through books and their authors.
- [Trust SQLite More Than Yourself]
- [Record Types are Responsible for Their Tables]
- [Compose Records]
- [Fetch In Time]
- [Observe the Database and Refetch when Needed]
## Trust SQLite More Than Yourself
SQLite is a robust 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 your application users. But thanks to SQLite, those bugs will be unable to corrupt your precious users' data. All it takes is a robust **database schema**.
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
varmigrator=DatabaseMigrator()
migrator.registerMigration("createLibrary"){dbin
trydb.create(table:"author"){tin//(1)
t.autoIncrementedPrimaryKey("id")//(2)
t.column("name",.text).notNull()//(3)
}
trydb.create(table:"book"){tin
t.autoIncrementedPrimaryKey("id")
t.column("title",.text).notNull()//(4)
t.column("authorId",.integer)//(5)
.notNull()//(6)
.indexed()//(7)
.references("author",onDelete:.cascade)//(8)
}
}
trymigrator.migrate(dbQueue)
```
1. Our database table names follow the GRDB 3 recommendation: generally speaking they should be singular, and camel-cased. Make them look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
2. Each author has a unique id.
3. An author must have a name.
4. A book must have a title.
5. The `book.authorId` column is used to link a book to the author it belongs to.
6. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
7. The `book.authorId` column is indexed in order to ease the selection of an author's books.
8. 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 so 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
> 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**.
## Record Types are Responsible for Their Tables
Define one record type per database table.
In this sample code, we'll use codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
That's it. The `Author` type can read and write in the `author` database table. `Book` as well, in `book`. See [record protocols] for more information.
> :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(with:for:)` method:
>
> ```swift
> var author = Author(id: nil, name: "Hermann Melville")
> try author.insert(db)
> print(author.id) // Some non-nil id
> ```
Since `Author` and `Book` can insert, update, and delete rows in the `author` and `book` database tables, they are *responsible for modifying those database tables*.
Applying the **[Single Responsibility Principle]** has a consequence: don't even try to have an author responsible for its books. Don't add a `books: [Book]` property in Author. Don't let Author write in the `book` table. When a new fellow coworker joins your team and asks you "who is saving books in the database?", you don't want to answer "it depends." You want to confidently answer: "the Book type".
> :bulb: **Tip**: Make sure each record type deals with one database table, and only one database table.
## Compose Records
Now that we have two types for authors and books, 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, along with their companion properties:
```swift
extensionAuthor{
staticletbooks=hasMany(Book.self)
varbooks:QueryInterfaceRequest<Book>{
returnrequest(for:Author.books)
}
}
extensionBook{
staticletauthor=belongsTo(Author.self)
varauthor:QueryInterfaceRequest<Author>{
returnrequest(for:Book.author)
}
}
```
Thanks to this setup, you can fetch associated records:
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
books=author.books# lazily fetches books on demand
```
GRDB does not perform lazy loading. Lazy loading either requires record 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. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information.
The consequence is that each part of 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] = dbQueue.read { db in
Author.order(Colum("name")).fetchAll(db)
}
```
2. 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
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(key: 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 the basic record types. Fetch the data your application needs, at the moment it needs it, no more, no less.
## Fetch In Time
> :bulb: **Tip**: Make sure you fetch all the data your application needs in a **single database read**.
```swift
// NOT RECOMMENDED
let bookId = 123
// Two fetches not grouped in a single `read` block:
if let book = databaseManager.getBook(id: bookId) {
let author = databaseManager.getAuthor(id: book.authorId)!
// use book and author
}
// RECOMMENDED (without associations)
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
// All fetches are grouped in a single `read` block:
if let book = try Book.fetchOne(db, key: bookId) {
let author = try Author.fetchOne(db, key: book.authorId)!
return BookInfo(book: book, author: author)
} else {}
return nil
}
}
if let bookInfo = bookInfo {
// use bookInfo
}
// RECOMMENDED (with associations)
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
// All fetches are grouped in a single `read` block:
let request = Book
.filter(key: bookId)
.including(required: Book.author)
return try BookInfo.fetchOne(db, request)
}
if let bookInfo = bookInfo {
// use bookInfo
}
```
This tip is paramount, and deserves an explanation because too many database libraries out there tend to completely disregard multi-threading gotchas.
When you do not fetch your data in a single database access block, other threads of your application may modify the database in the background, and have you fetch inconsistent data. This leads to hard-to-reproduce bugs, from funny values on screen to data loss.
Wrapping all fetches in a `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
```ruby
# Ruby's Active Record
if book = Book.find(123) # fetch book
author = book.author # fetch author
# use book and author
end
```
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 with database access methods such as `dbQueue.read`.
Do not overlook this advice, or your application will exhibit weird concurrency-related bugs. Read 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 Author and Book record types are [responsible](#record-types-are-responsible-for-their-tables) for their own dedicated database tables. Later we [composed](#compose-records) them into more complex types such as `BookInfo` or `AuthorInfo`. We advised the application to fetch database information [right on time](#fetch-in-time), when it needs to process it.
Fetched information 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**: Use [FetchedRecordsController] when a table or collection views should remained synchronized with the database, in an animated way.
>
> :bulb: **Tip**: Use [RxGRDB] when your application needs to react to all changes in the results of a database request.
>
> :bulb: **Tip**: Use [TransactionObserver], the low-level protocol for 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.
**The [query interface] is a Swift API that approximates the [SQLite SELECT query grammar](https://sqlite.org/lang_select.html) through a hierarchy of values and protocols.**
This document describes its inner organization, so that you can make the most of those types and protocols when you want it.
In the diagram below, protocols are pale blue and have rounded corners, and standard types are grey rectangles. Solid arrows read "inherits from", and dashed arrows read "produces". Generic types are marked as such, as well as "PATs" (protocols with associated types).
`Association` is the protocol for all [associations]. It is adopted by `BelongsToAssociation`, `HasManyAssociation`, etc. It conforms to [DerivableRequest].
```swift
protocolAssociation:DerivableRequest{
associatedtypeOriginRowDecoder
funcforKey(_key:String)->Self
}
```
Association has two sub-protocols:
```swift
protocolAssociationToOne:Association{}
protocolAssociationToMany:Association{}
```
`AssociationToMany`, adopted by `HasManyAssociation` and `HasManyThroughAssociation`, leverages [association aggregates].
### Column
`Column` is the type for database columns. It conforms to [ColumnExpression].
```swift
Column("name")
Column("id")
Column.rowID
```
### ColumnExpression
`ColumnExpression` is the protocol for database columns. It is adopted by [Column]. It conforms to [SQLSpecificExpressible].
```swift
protocolColumnExpression:SQLSpecificExpressible{
///Thenameofadatabasecolumn.
varname:String{get}
}
```
Columns can be used, for example, to query database rows:
```swift
letrow=tryRow.fetchOne(db,sql:"SELECT 'Arthur' AS name")!
letname:String=row[Column("name")]//"Arthur"
```
Columns are special expressions that allow some optimizations and niceties:
- Database observation: When a request is limited to a known list of rowids in a database table, changes applied to other rows do not trigger the observation. GRDB needs column expressions in order to apply this optimization:
```swift
// Optimized Observations
ValueObservation.tracking { db in
try Player.fetchOne(db, id: 1)
// or
try Player.filter { $0.id == 1 }.fetchOne(db)
}
// Non-optimized observations
ValueObservation.tracking { db in
try SQLRequest<Player>("SELECT * FROM player WHERE id = 1").fetchOne(db)
// or
try Player.filter(sql: "id = 1").fetchOne(db)
}
```
- SQL generation: when it generates SQL queries, GRDB appends `LIMIT 1` or not, depending on the primary key and unique indexes used on the queried table. GRDB needs column expressions in order to improve its SQL generation:
```swift
// Nicer SQL
// SELECT * FROM player WHERE id = 1
try Player.fetchOne(db, id: 1)
try Player.filter { $0.id == 1 }.fetchOne(db)
// Less nice SQL
// SELECT * FROM player WHERE id = 1 LIMIT 1
try Player.filter(sql: "id = 1").fetchOne(db)
```
### DatabaseRegionConvertible
`DatabaseRegionConvertible` is the protocol for observable requests. It is adopted by [FetchRequest].
DatabaseRegionConvertible feeds [DatabaseRegionObservation], which tracks database transactions that impact a particular database region:
```swift
let request = Player.all()
let observation = DatabaseRegionObservation(tracking: request)
let cancellable = observation.start(in: dbQueue) { error in
// Handle error
} onChange: { (db: Database) in
print("Players were changed")
}
```
### DatabaseValue
`DatabaseValue` is the type for SQL values (integers, doubles, strings, blobs, and NULL). It conforms to [SQLSpecificExpressible].
You generally build a DatabaseValue from a [DatabaseValueConvertible] type:
```swift
1.databaseValue
"Hello".databaseValue
DatabaseValue.null
```
The query interface will sometimes not accept raw [SQLExpressible] values such as [Int, String, Date], etc. In this case, turn those values into DatabaseValue so that you leverage APIs that need [SQLSpecificExpressible]. For example:
```swift
// SQL: firstName || ' ' || lastName
let fullname = [
Column("firstName"),
" ".databaseValue,
Column("lastName"),
].joined(operator: .concat)
```
### DatabaseValueConvertible
`DatabaseValueConvertible` is the protocol for types that can provide [DatabaseValue]: SQL integers, doubles, strings, blobs, and NULL. It is adopted by [Int, String, Date], etc. It conforms to [SQLExpressible] because all SQL values are SQL expressions.
`DerivableRequest` is the protocol for query interface requests and associations that can be refined. It is adopted by [QueryInterfaceRequest] and [Association].
- `AggregatingRequest` provides grouping methods such as `groupByPrimaryKey()`
- `FilteredRequest` provides filtering methods such as `filter(expression)` or `filter(id: value)`
- `JoinableRequest` provides association methods such as `joining(required: association)` or `including(all: association)`
- `OrderedRequest` provides ordering methods such as `order(ordering)` or `reversed()`
- `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).
### FetchRequest
`FetchRequest` is the protocol for requests that can fetch. It is adopted by [QueryInterfaceRequest] and [SQLRequest]. It conforms to [SQLSubqueryable] and [DatabaseRegionConvertible].
/// Returns the number of rows fetched by the request.
func fetchCount(_ db: Database) throws -> Int
}
```
FetchRequest can fetch values from the database as long as its `RowDecoder` associated type is `Row`, a [DatabaseValueConvertible] type, or a [FetchableRecord] type.
```swift
let row: Row? = try SQLRequest<Row>("SELECT * FROM player").fetchOne(db)
let players: [Player] = try Player.all().fetchAll(db)
```
FetchRequest usually executes a single SQL query:
```swift
// SELECT * FROM player
let request = Player.all()
try request.fetchAll(db)
```
This single SQL query is exposed through `makePreparedRequest(_:forSingleResult:)`:
```swift
let request = Player.all()
let preparedRequest = try request.makePreparedRequest(db)
print(preparedRequest.statement.sql) // SELECT * FROM player
```
But not all fetch requests execute a single SQL query. A [QueryInterfaceRequest] that involves [associations] can execute several:
```swift
// SELECT * FROM player
// SELECT * FROM award WHERE playerId IN (...)
struct PlayerInfo: Decodable, FetchableRecord {
var player: Player
var awards: [Award]
}
let playerInfos = try Player
.including(all: Player.awards)
.asRequest(of: PlayerInfo.self)
.fetchAll(db)
```
Those supplementary SQL queries are an implementation detail of `PreparedRequest`, and are not currently exposed.
### Int, String, Date…
The basic value types conform to [DatabaseValueConvertible] so that they can feed database queries with [DatabaseValue]:
```swift
// SELECT * FROM player WHERE name = 'O''Brien'
// ~~~~~~~~~~
Player.filter { $0.name == "O'Brien" }
```
### QueryInterfaceRequest
`QueryInterfaceRequest` is the type of fetch requests built by the GRDB query builder. It conforms to [FetchRequest] and [DerivableRequest].
It is generic on the type of fetched values:
```swift
struct PlayerInfo: Decodable, FetchableRecord {
var player: Player
var awards: [Award]
}
// QueryInterfaceRequest<Player>
let playerRequest = Player.all()
// QueryInterfaceRequest<String>
let nameRequest = Player.select(Column("name"), as: String.self)
For more information on QueryInterfaceRequest, see [Requests](../README.md#requests) and [Associations](AssociationsBasics.md).
### SQL
`SQL` is the type for SQL literals that support [SQL Interpolation]. It can feed all GRDB APIs that have a `literal` argument:
```swift
let literal: SQL = "SELECT * FROM player"
let request = SQLRequest<Player>(literal: literal)
let players: [Player] = try request.fetchAll(db)
```
`SQL` conforms to [SQLSpecificExpressible], and thus behaves as an [SQLite expression](https://sqlite.org/syntax/expr.html) by default:
```swift
let literal: SQL = "name = \("O'Brien")"
let request = Player.filter(literal)
let players: [Player] = try request.fetchAll(db)
```
:warning: **Warning**: Not all SQL snippets are expressions. It is not recommended to pass `SQL` literals around, or you may end up forgetting their content, and eventually generate invalid SQL. When possible, prefer building an explicit [SQLExpression], [SQLOrdering], [SQLSelection], [SQLRequest], or [SQLSubquery], depending on what you want to express:
```swift
// SQLExpression
SQL("name = \("O'Brien")").sqlExpression
// SQLOrdering
SQL("name DESC").sqlOrdering
// SQLSelection
SQL("score + bonus AS total").sqlSelection
SQL("*").sqlSelection
// SQLRequest
SQLRequest<Player>(literal: "SELECT * FROM player")
// SQLSubquery
SQLRequest(literal: "SELECT * FROM player").sqlSubquery
```
### SQLExpression
`SQLExpression` is the opaque type for all [SQLite expressions](https://sqlite.org/syntax/expr.html). It adopts [SQLSpecificExpressible], and is built from [SQLExpressible].
```swift
struct SQLExpression: SQLSpecificExpressible {
// opaque implementation
}
```
Functions and methods that build an SQL expression should return an SQLExpression value:
```swift
// SELECT * FROM player WHERE LENGTH(name) > 0
Player.filter {
length($0.name) > 0 // SQLExpression
}
```
When it looks like GRDB APIs are unable to build a particular expression, use [SQL]:
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
let request = Player.filter { date($0.createdAt) == "2020-01-23" }
```
This technique, based on [SQL Interpolation], is composable and works well even when several tables are involved. See how the `createdAt` column below is correctly attributed to the `player` table:
```swift
// SELECT player.*, team.* FROM player
// JOIN team ON team.id = player.teamId
// WHERE DATE(player.createdAt) = '2020-01-23'
let request = Player
.filter { date($0.createdAt) == "2020-01-23" }
.including(required: Player.team)
```
### SQLExpressible
`SQLExpressible` is the protocol for all [SQLite expressions](https://sqlite.org/syntax/expr.html). It is adopted by [Column], [SQL], [SQLExpression], and also [Int, String, Date], etc. It has an `sqlExpression` property which returns an [SQLExpression].
```swift
protocol SQLExpressible {
var sqlExpression: SQLExpression { get }
}
```
SQLExpressible-conforming types include types which are not directly related to SQL, such as [Int, String, Date], etc. Because of this, SQLExpressible has limited powers that prevent misuses and API pollution. For full-fledged SQL expressions, see [SQLSpecificExpressible]. For example, compare:
```swift
Player.filter(1) // Compiler warning (will become an error in the next major release)
Player.select(1) // Compiler error
Player.order("name") // Compiler error
length("name") // Compiler error
"name".desc // Compiler error
```
```swift
Player.filter(id: 1) // OK
Player.filter(1.databaseValue) // Odd, but OK
Player.select(1.databaseValue) // Odd, but OK
Player.order(Column("name")) // OK
length(Column("name")) // OK
Column("name").desc // OK
```
### SQLOrderingTerm
`SQLOrderingTerm` is the protocol for all [SQLite ordering terms](https://sqlite.org/syntax/ordering-term.html). It is adopted by [SQLSpecificExpressible]. It has an `sqlOrdering` property which returns an [SQLOrdering].
```swift
protocol SQLOrderingTerm {
var sqlOrdering: SQLOrdering { get }
}
```
SQLOrderingTerm feeds the `order()` method of the query interface:
All [SQLSpecificExpressible] values are ordering terms. [SQLExpressible] values are not: `Player.order("name")` does not compile. Instead, use:
```swift
// SELECT * FROM player ORDER BY name -- Order according to a column
Player.order(Column("name"))
// SELECT * FROM player ORDER BY 'name' -- Order according to a constant string (why not)
Player.order("name".databaseValue)
```
### SQLOrdering
`SQLOrdering` is the opaque type for all [SQLite ordering terms](https://sqlite.org/syntax/ordering-term.html). An SQLOrdering adopts and is built from [SQLOrderingTerm].
```swift
struct SQLOrdering: SQLOrderingTerm {
// opaque implementation
}
```
Functions and methods that build ordering terms should return an SQLOrdering value:
```swift
// SELECT * FROM player ORDER BY score DESC
let ordering = Column("score").desc // SQLOrdering
Player.order(ordering)
```
To build an SQLOrdering without applying any `DESC` or `ASC` qualifier, use `sqlOrdering` (from [SQLOrderingTerm], inherited by [SQLSpecificExpressible], [ColumnExpression]...):
```swift
let ordering = Column("score").sqlOrdering // SQLOrdering
```
### SQLRequest
`SQLRequest` is the type of fetch requests expressed with raw SQL. It conforms to [FetchRequest].
It is generic on the type of fetched values (which defaults to `Row`):
```swift
let rowRequest = SQLRequest(sql: "SELECT * FROM player") // SQLRequest<Row>
let playerRequest = SQLRequest<Player>(sql: "SELECT * FROM player") // SQLRequest<Player>
let nameRequest = SQLRequest<String>(sql: "SELECT name FROM player") // SQLRequest<String>
try rowRequest.fetchAll(db) // [Row]
try playerRequest.fetchAll(db) // [Player]
try nameRequest.fetchAll(db) // [String]
try rowRequest.fetchOne(db) // Row?
try playerRequest.fetchOne(db) // Player?
try nameRequest.fetchOne(db) // String?
```
SQLRequest supports [SQL Interpolation]:
```swift
// SELECT * FROM player WHERE name = 'O''Brien'
let playerRequest: SQLRequest<Player> = """
SELECT * FROM player WHERE name = \("O'Brien")
"""
```
### SQLSelectable
`SQLSelectable` is the protocol for all [SQLite result columns](https://sqlite.org/syntax/result-column.html). It is adopted by [SQLSpecificExpressible]. It has an `sqlSelection` property which returns an [SQLSelection].
```swift
protocol SQLSelectable {
var sqlSelection: SQLSelection { get }
}
```
SQLSelectable feeds the `select()` method of the query interface:
```swift
Player.select(.allColumns)
Player.select(Column("name"), Column("score"))
```
All [SQLSpecificExpressible] values are selectable. Other selectable values are:
[SQLExpressible] values are not selectable: `Player.select("name")` does not compile. Instead, use:
```swift
// SELECT name FROM player -- Selects a column
Player.select(Column("name"))
// SELECT 'name' FROM player -- Selects a constant string (why not)
Player.select("name".databaseValue)
```
### SQLSelection
`SQLSelection` is the opaque type for all [SQLite result columns](https://sqlite.org/syntax/result-column.html). An SQLSelection adopts and is built from [SQLSelectable].
```swift
struct SQLSelection: SQLSelectable {
// opaque implementation
}
```
Functions and methods that build result columns should return an SQLSelection value:
```swift
// SELECT (score + bonus) AS total
let selection = (Column("score") + Column("bonus")).forKey("total") // SQLSelection
Player.select(selection)
```
### SQLSpecificExpressible
`SQLSpecificExpressible` is the protocol for all SQL expressions, except values such as [Int, String, Date], etc. It conforms to [SQLExpressible], [SQLSelectable], and [SQLOrderingTerm]. It is adopted by [Column], [SQL], and [SQLExpression]. It is also adopted through [SQLSubqueryable] by [QueryInterfaceRequest] and [SQLRequest].
Use SQLSpecificExpressible when you want to operate on expressions, except [Int, String, Date] and other types which are not directly related to SQL. For example, the built-in `length(_:)` GRDB function accepts SQLSpecificExpressible:
`SQLSubquery` is the opaque type for all [SQLite SELECT queries](https://sqlite.org/syntax/select-stmt.html). An SQLSubquery adopts and is built from [SQLSubqueryable].
```swift
struct SQLSubquery: SQLSubqueryable {
// opaque implementation
}
```
### SQLSubqueryable
`SQLSubqueryable` is the protocol for all [SQLite SELECT queries](https://sqlite.org/syntax/select-stmt.html). It conforms to [SQLSpecificExpressible], and is adopted by [FetchRequest], [QueryInterfaceRequest], [SQLRequest]. It has an `sqlSubquery` property which returns an [SQLSubquery].
Your SQL skills are [welcomed] throughout GRDB. Yet writing raw SQL presents commonplace challenges. For example, you want to make sure your queries don't break whenever the database schema changes as you ship new versions of your application. When you inject user values in the database, you have to use statement arguments, and it is easy to make a mistake in the process.
The query below exemplifies this situation. It even contains a bug that is not quite easy to spot:
```swift
trydbQueue.write{dbin
trydb.execute(
sql:"""
UPDATE student
SET firstName = ?, lastName = ?, department = ?, birthDate = ?,
**SQL Interpolation** lets you embed values in your SQL queries by wrapping them inside `\(` and `)`:
```swift
letname:String=...
letid:Int64=...
trydbQueue.write{dbin
trydb.execute(literal:"UPDATE player SET name = \(name) WHERE id = \(id)")
}
```
SQL interpolation looks and feels just like regular [String interpolation]:
```swift
letname="World"
print("Hello \(name)!")//prints"HelloWorld!"
```
The difference is that it generates valid SQL which does not suffer from syntax errors or [SQL injection]. For example, you do not need to validate input or process single quotes:
trydb.execute(literal:"UPDATE player SET name = \(name) WHERE id = \(id)")
}
```
Plain SQL strings are indeed still available, and SQL interpolation only kicks in when you ask for it. There is a simple rule to remember:
- For plain SQL strings, use the `sql` argument label:
```swift
try db.execute(sql: "UPDATE player SET name = ? WHERE id = ?", arguments: [name, id])
```
- For SQL interpolation, use the `literal` argument label:
```swift
try db.execute(literal: "UPDATE player SET name = \(name) WHERE id = \(id)")
```
## SQL Literal
**`SQL`** is the type that looks like a plain String, but profits from SQL interpolation:
```swift
try dbQueue.write { db in
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
try db.execute(literal: query)
}
```
**`SQL` is not a Swift String.** You cannot use the `execute(literal:)` method with a String argument:
```swift
try dbQueue.write { db in
let query = "UPDATE player SET name = \(name) WHERE id = \(id)" // a regular String
// Compiler error:
// Cannot convert value of type 'String' to expected argument type 'SQL'
try db.execute(literal: query)
}
```
`SQL` can build your queries step by step, with regular operators and methods:
```swift
// +, +=, append
var query: SQL = "UPDATE player "
query += "SET name = \(name) "
query.append(literal: "WHERE id = \(id)")
// joined(), joined(separator:)
let components: [SQL] = [
"UPDATE player",
"SET name = \(name)",
"WHERE id = \(id)"
]
let query = components.joined(separator: " ")
```
To extract the plain SQL string from a literal, you need a `Database` connection such as the one provided by the `read` and `write` methods:
```swift
try dbQueue.read { db in
let query: SQL = "UPDATE player SET name = \(name) WHERE id = \(id)"
let (sql, arguments) = try query.build(db)
print(sql) // prints "UPDATE player SET name = ? WHERE id = ?"
print(arguments) // prints ["O'Brien", 42]
}
```
Build a literal from a plain SQL string:
```swift
let query = SQL(
sql: "UPDATE player SET name = ? WHERE id = ?",
arguments: [name, id])
```
`SQL` can embed any [value], as we have seen above, and more. Please keep on reading the next chapter, or jump directly to the [SQL Interpolation Reference].
## SQL Interpolation and the Query Interface
SQL Interpolation and `SQL` let you embed raw SQL snippets in [query interface requests].
For example:
```swift
// SELECT * FROM player WHERE name = 'O''Brien'
let request = Player.filter(literal: "name = \("O'Brien")")
```
You can also build literals from other expressions. For example, let's call the `DATE` SQLite function on a query interface column:
```swift
// SELECT * FROM player WHERE DATE(createdAt) = '2020-01-23'
let createdAt = Column("createdAt")
let creationDay = SQL("DATE(\(createdAt))")
let request = Player.filter(creationDay == "2020-01-23")
```
Such literals play well with the query interface, even when several tables are involved with [associations](AssociationsBasics.md):
```swift
// SELECT player.*, team.*
// FROM player
// JOIN team ON team.id = player.teamID
// WHERE DATE(player.createdAt) = '2020-01-23'
// ~~~~~~~~~~~~~~~~~~~~~~
// automatic table disambiguation
let request = Player
.filter(creationDay == "2020-01-23")
.including(required: Player.team)
```
This allows you to define Swift functions that you can use in all circumstances:
let request = Player.filter { date($0.createdAt) == "2020-01-23" }
```
## SQL Interpolation and Record Protocols
The [record protocols] extend your application types with database abilities.
**A record type knows everything about the schema of its underlying database table**. With the [TableRecord] protocol, the `databaseTableName` property contains the table name. With the [Decodable] protocol, the [CodingKeys] enum contains the column names. And with [FetchableRecord], you can decode raw database rows.
SQL Interpolation puts this knowledge to good use, so that you can build robust queries that consistently use correct table and column names. Let's start from this record:
try db.execute(literal: "DELETE FROM \(self) WHERE \(CodingKeys.score) IS NULL")
}
}
```
Usage:
```swift
try dbQueue.write { db in
// DELETE FROM player WHERE score IS NULL
try Player.deleteAllWithoutScore(db)
}
```
`DELETE FROM \(self) ...` embeds the Player type itself. Since Player adopts the [TableRecord] protocol, this embeds `Player.databaseTableName` in the SQL query.
`... \(CodingKeys.score) IS NULL` embeds CodingKeys.score. This one has been synthesized by the Swift compiler because Player adopts the Decodable protocol. It embeds the column name in the SQL query.
The return type of this method is `SQLRequest<Player>`. It is one of the GRDB [request types]. It profits from SQL interpolation, and this is why this method simply returns an "SQL literal".
The first "simple" version only embeds the `\(id)` [value].
The second "robust" version embeds `\(columnsOf: self)`, the [columns selected by the record](#columns-selected-by-a-request), `\(self)` (the Player type which adopts the TableRecord protocol), `\(CodingKeys.id)` (the coding key synthesized by the Decodable protocol), and the `\(id)` [value].
It embeds `\(ids)`, an array of ids. All [value] sequences are supported (arrays, sets, etc.) Empty sequences are supported as well, with both `IN` and `NOT IN` SQL operators.
The result is `SQLRequest<Int>`, unlike previous requests of type `SQLRequest<Player>`. SQLRequest accepts any fetchable type (database [row], simple [value], or custom [record]).
"SELECT * FROM player WHERE score = (\(maximumScore()))"
}
/// "Future-proof" version
static func bestPlayers() -> SQLRequest<Player> {
"""
SELECT \(columnsOf: self)
FROM \(self)
WHERE \(CodingKeys.score) = (\(maximumScore()))
"""
}
}
```
Usage:
```swift
let bestPlayers = try dbQueue.read { db in
// SELECT * FROM player WHERE score = (SELECT MAX(score) FROM player)
try Player.bestPlayers().fetchAll(db) // [Player]
}
```
This request embeds `\(maximumScore())`, the `SQLRequest<Int>` returned by the `maximumScore` method. After values, coding keys, and types that adopt the TableRecord protocol, this ends our quick tour of things you can embed between `\(` and `)`. Check out the [SQL Interpolation Reference] for the full list of supported interpolations.
Loaded 100 of 935 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.