After failed experiment:
SELECT ...
FROM parent
JOIN (SELECT * FROM child LIMIT 1) child ON child.parentId = child.id
The problem is that the join condition can't go inside the subquery, because SQLite complains about unknown table "parent". And when the join condition is outside the subquery, the LIMIT clause has been applied too early.
So we're still stuck with:
SELECT ...
FROM parent
JOIN child ON child.id = (SELECT id FROM child WHERE child.parentId = child.id LIMIT 1)
For some reason SQLite accepts the reference to the parent table in this case.
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.
Rename AssociationMapping to JoinCondition
Replace AssociationMappingRequest enum with ForeignKeyJoinConditionRequest struct
Rename AssociationChainOperator to AssociationJoinOperator, and "chain" to "join"
Those request protocols allow types that are not QueryInterfaceRequest to expose the same derivation API. This is a necessary step towards associations.
Those types bloat the documentation for no real value: DropFirstCursor, DropWhileCursor, EnumeratedCursor, FilterCursor, FlattenCursor, MapCursor, PrefixCursor, PrefixWhileCursor
- Upgrade Tests/SPM package layout and format to version 4, and have `make test_install_SPM` succeed
- Update .gitignore in order to ignore Package.resolved instead of Package.pins
The goal of those tests is to prevent breaking changes as the one that happened in v1.2, where the DatabaseReader protocol was added a new method without any default implementation.
2017-07-13 16:53:01 +02:00
627 changed files with 108272 additions and 39035 deletions
> 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.
This guide is a set of tips and guidelines for contributing to the GitHub repository [groue/GRDB.swift](https://github.com/groue/GRDB.swift).
- [Report Bugs]
- [Ask Questions]
- [Suggest an Enhancement]
- [Submit a Pull Request]
- [Sponsoring and Professional Support]
- [Suggested Contributions]
- [Non-Goals]
### Report Bugs
Please make sure the bug is not already reported by searching existing [issues](https://github.com/groue/GRDB.swift/issues).
If you're unable to find an existing issue addressing the problem, [open a new one](https://github.com/groue/GRDB.swift/issues/new). Be sure to include a title and clear description, as much relevant information as possible, and a code sample or an executable test case demonstrating the expected behavior that is not occurring.
### Ask Questions
The information you are looking for is maybe already available. Check out:
- the [FAQ](README.md#faq)
- the [general documentation](README.md#documentation)
- the [answered questions](https://github.com/groue/GRDB.swift/issues?utf8=✓&q=label%3Aquestion+)
If not, your questions are welcome in the [GRDB forums](https://forums.swift.org/c/related-projects/grdb), or in a new [GitHub issue](https://github.com/groue/GRDB.swift/issues/new).
### Suggest an Enhancement
Your idea may already be listed in [Suggested Contributions], waiting for someone to pick it up.
If not, contact [@groue](http://twitter.com/groue) on Twitter, or [open a new issue](https://github.com/groue/GRDB.swift/issues/new).
### Submit a Pull Request
Discuss your idea first, so that your changes have a good chance of being merged in.
Submit your pull request against the `development` branch.
Pull requests that include tests for modified and new functionalities, inline documentation, and relevant updates to the main README.md are merged faster, because you won't have to wait for somebody else to complete your contribution.
### Sponsoring and Professional Support
GRDB is free. It is openly developed by its contributors, on their free time, according to their will, needs, and availability. It is not controlled by any company.
When you have specific development or support needs, and are willing to financially contribute to GRDB, 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.
## Suggested Contributions
You'll find below various ideas for enhancing and extending GRDB, in various areas. Your ideas can be added to this list: [Suggest an Enhancement].
Legend:
- :baby: **Starter Task**: get familiar with GRDB internals
- :muscle: **Hard**: there are implementation challenges
- :pencil: **Documentation**
- :fire: **Experimental**: let's invent the future!
- :bowtie: **Public API Challenge**: we'll need a very good public API
- :hammer: **Tooling**: GRDB and its environment
- :question: **Unknown Difficulty**
The ideas, in alphabetical order:
- [Associations]
- [CloudKit]
- [Concurrency]
- [Custom FTS5 Auxiliary Functions]
- [Date and Time Functions]
- [Decode NSDecimalNumber from Text Columns]
- [Documentation]
- [Full Text Search Demo Application]
- [JSON]
- [Linux]
- [More SQL Generation]
- [Reactive Database Observation]
- [SQL Console in the Debugger]
- [SQLCipher in a Shared App Container]
- [Typed Expressions]
### Associations
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
Associations can be enhanced in several ways. See the "Known Issues" chapter of the [Associations Guide](Documentation/AssociationsBasics.md)
### CloudKit
:bowtie: Public API Challenge :question: Unknown Difficulty :fire: Experimental
Integration with [CloudKit](https://developer.apple.com/icloud/cloudkit/) is a rich, interesting, and useful topic.
It is likely that CloudKit support would exist in a separate companion library.
- [Synchronizing data with CloudKit](https://medium.com/@guilhermerambo/synchronizing-data-with-cloudkit-94c6246a3fda)
- WWDC CloudKit sessions, including [CloudKit Best Practices](https://developer.apple.com/videos/play/wwdc2016/231/)
### Concurrency
:bowtie: Public API Challenge :muscle: Hard :pencil: Documentation
GRDB has a strong focus on safe concurrency. Not only safe as "does not crash", but safe as "actively protects your application data". The topic is discussed in (too) many places:
- [Four different ways to handle SQLite concurrency](https://medium.com/@gwendal.roue/four-different-ways-to-handle-sqlite-concurrency-db3bcc74d00e)
- [Good Practices for Designing Record Types](https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md#fetch-in-time)
- [Comparison between GRDB and Core Data concurrency](https://github.com/groue/GRDB.swift/issues/405)
Despite this abundant documention, I regularly meet developers who don't think about eventual multi-threading gotchas, and don't design their application against them.
This can be explained:
- Some developers disregard potential multi-threading bugs such as data races, even if the fix is "easy". Such bugs may never happen during the development of an application. They may only impact a few users in production. It is always easier not to think about them.
- Databases are often seen as plain CRUD tools, and some developers are not familiar with topics like isolation or transactions. This is especially true for developers who have experience in a managed ORM such as Core Data or Realm, or web frameworks like Rails or Django: switching to an unmanaged relational database is not an easy task.
- Not all applications need to be multi-threaded.
And this creates improvement opportunities:
- Better documentation of GRDB concurrency
- The introduction of an "ultra-safe" concurrency mode. Maybe something that restricts all database accesses to the main thread, like [FCModel](https://github.com/marcoarment/FCModel). Maybe in a separate companion library.
### Custom FTS5 Auxiliary Functions
:question: Unknown Difficulty
The SQLite documentation provides [this description](https://www.sqlite.org/fts5.html) of FTS5 auxiliary functions:
> An application may use FTS5 auxiliary functions to retrieve extra information regarding the matched row. For example, an auxiliary function may be used to retrieve a copy of a column value for a matched row with all instances of the matched term surrounded by html <b></b> tags.
Applications can define their own [custom FTS5 auxiliary functions](https://www.sqlite.org/fts5.html#custom_auxiliary_functions) with SQLite, but GRDB does not yet provide any Swift API for that.
See issue [#421](https://github.com/groue/GRDB.swift/issues/421) for more information.
### Date and Time Functions
:baby: Starter Task
Believe it or not, no one has ever asked support for SQLite [Date And Time Functions](https://www.sqlite.org/lang_datefunc.html). There is surely room for a nice Swift API that makes them available.
- [SQLite JSON functions](https://www.sqlite.org/json1.html) and [JSON], below.
Functions are defined in [GRDB/QueryInterface/Support/SQLFunctions.swift](https://github.com/groue/GRDB.swift/blob/master/GRDB/QueryInterface/Support/SQLFunctions.swift).
### Decode NSDecimalNumber from Text Columns
:baby: Starter Task
NSDecimalNumber currently only decodes integer and float decimal values. It would be nice if NSDecimalNumber would decode text values as well:
NSNumber and NSDecimalNumber support is found in [GRDB/Core/Support/Foundation/NSNumber.swift](https://github.com/groue/GRDB.swift/blob/master/GRDB/Core/Support/Foundation/NSNumber.swift)
### Documentation
:baby: Starter Task :pencil: Documentation
General documentation can always be improved so that it reaches its goal: helping developers building applications.
- English: the documentation has mostly been written by [@groue](http://github.com/groue) who is not a native English speaker.
- Clarity: any chapter that is not crystal clear should be enhanced.
- Audience: documentation should talk to several populations of developers, from beginners who need positive guidance, to SQLite experts who need to build trust.
- Typos
- Inaccuracies
- etc.
Inline documentation, the one which is embedded right into the source code and is displayed by Xcode when one alt-clicks an identifier, deserves the same care.
If you are a good writer, your help will be very warmly welcomed.
### Full Text Search Demo Application
:baby: Starter Task :pencil: Documentation
There exists a GRDB demo app for the FTS5 full-text engine: [WWDCCompanion](https://github.com/groue/WWDCCompanion).
This application downloads the transcripts of WWDC sessions, and lets its user type keywords and find matching sessions, sorted by relevance.
The problem is that this demo app breaks every year :sweat_smile:
We'd need instead to index a stable corpus, in order to ease the maintenance of this demo app.
### JSON
:bowtie: Public API Challenge :baby: Starter Task
[Codable Records] are granted with automatic JSON encoding and decoding of their complex properties. But there is still room for improvements. For example, could we put the [SQLite JSON1 extension](https://www.sqlite.org/json1.html) to some good use?
### Linux
:muscle: Hard :hammer: Tooling
Swift on Linux is currently focused on the server (Vapor, Perfect, Kitura). While general server support is a [non-goal](#non-goals) of GRDB, there exists read-only servers, and Linux GUI applications, too. Linux is thus a desired platform.
### More SQL Generation
:bowtie: Public API Challenge :question: Unknown Difficulty
There are several SQLite features that GRDB could natively support:
- [ALTER TABLE ... RENAME COLUMN ... TO ...](https://www.sqlite.org/lang_altertable.html)
See [issue #575](https://github.com/groue/GRDB.swift/issues/575) for more information and guidance about the implementation of extra table alterations.
### Reactive Database Observation
:baby: Starter Task
We already have the [GRDBCombine](http://github.com/groue/GRDBCombine) and [RxGRDB] companion libraries.
More choices of reactive engines would help more developers enjoy GRDB.
### SQL Console in the Debugger
:question: Unknown Difficulty :hammer: Tooling
Sometimes one needs, in lldb, a console similar to the [Command Line Shell For SQLite](https://www.sqlite.org/cli.html).
### SQLCipher in a Shared App Container
:question: Unknown Difficulty
See issue [#302](https://github.com/groue/GRDB.swift/issues/302).
### Typed Expressions
:bowtie: Public API Challenge :muscle: Hard :fire: Experimental
The compiler currently does not spot type mistakes in query interface requests:
```swift
Player.filter(Column("name")=="Arthur")//OK
Player.filter(Column("name")==1)//Sure
Player.filter(Column("name")==Date())//Legit
```
This weak typing also prevents natural-looking Swift code from producing the expected results:
It would be interesting to see what typed expressions could bring to GRDB.
## Non-Goals
GRDB is a "toolkit for SQLite databases, with a focus on application development".
This definition is the reason why GRDB can provide key features such as sharp multi-threading, database observation, and first-class support for raw SQL.
Features that blur this focus are non-goals:
- Support for MySQL, PostgreSQL, or other database engines
[Records: Splitting Database Encoding from Ability to Write in the Database]: #records-splitting-database-encoding-from-ability-to-write-in-the-database
On iOS, you can share database files between multiple processes by storing them in an [App Group Container](https://developer.apple.com/documentation/foundation/nsfilemanager/1412643-containerurlforsecurityapplicati).
A shared database is accessed from several SQLite connections, from several processes. This creates challenges at various levels:
1.**Database setup** may be attempted by multiple processes, concurrently.
2.**SQLite** may throw `SQLITE_BUSY` errors, code 5, "database is locked".
3.**iOS** may kill your application with a `0xDEAD10CC` exception.
4.**GRDB** database observation misses changes performed by external processes.
We'll address all of those challenges below.
- [Use a Database Pool]
- [How to limit the `SQLITE_BUSY` error]
- [How to limit the `0xDEAD10CC` exception]
- [How to perform cross-process database observation]
## Use a Database Pool
In order to access a shared database, use a [Database Pool]. It opens the database in the [WAL mode](https://www.sqlite.org/wal.html), which helps sharing a database.
Since several processes may open the database at the same time, protect the creation of the database pool with an [NSFileCoordinator].
- In a process that can create and write in the database, use this sample code:
```swift
/// Returns an initialized database pool at the shared location databaseURL
let dbPool = try DatabasePool(path: databaseURL.path, configuration: configuration)
// Check here if the database schema is correct, for example
// with a DatabaseMigrator.
if try dbPool.read(migrator.hasCompletedMigrations) {
return dbPool
} else {
return nil
}
} catch {
if FileManager.default.fileExists(atPath: databaseURL.path) {
throw error
} else {
return nil
}
}
}
```
## How to limit the `SQLITE_BUSY` error
> The SQLITE_BUSY result code indicates that the database file could not be written (or in some cases read) because of concurrent activity by some other database connection, usually a database connection in a separate process.
See https://www.sqlite.org/rescode.html#busy for more information about this error.
If several processes want to write in the database, configure the database pool of each process that wants to write:
```swift
var configuration = Configuration()
configuration.busyMode = .timeout(/* a TimeInterval */)
configuration.defaultTransactionKind = .immediate
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
With such a setup, you may still get `SQLITE_BUSY` (5, "database is locked") errors from all write operations. They will occur if the database remains locked by another process for longer than the specified timeout.
```swift
do {
try dbPool.write { db in ... }
} catch let error as DatabaseError where error.resultCode == .SQLITE_BUSY {
// Another process won't let you write. Deal with it.
}
```
> :bulb: **Tip**: In order to be nice to other processes, measure the duration of your longest writes, and attempt at optimizing the ones that last for too long.
## How to limit the `0xDEAD10CC` exception
> The exception code 0xDEAD10CC indicates that an application has been terminated by the OS because it held on to a file lock or sqlite database lock during suspension.
See https://developer.apple.com/library/archive/technotes/tn2151/_index.html for more information about this exception.
1. If you use SQLCipher, use SQLCipher 4+, and call the `cipher_plaintext_header_size` pragma from your database preparation function:
```swift
var configuration = Configuration()
configuration.prepareDatabase = { (db: Database) in
let dbPool = try DatabasePool(path: ..., configuration: configuration)
```
Post `Database.suspendNotification` when the application is about to be [suspended](https://developer.apple.com/documentation/uikit/app_and_environment/managing_your_app_s_life_cycle). You can for example post this notification from `UIApplicationDelegate.applicationDidEnterBackground(_:)`, or in the expiration handler of a [background task](https://forums.developer.apple.com/thread/85066).
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
Post `Database.resumeNotification` from `UIApplicationDelegate.applicationWillEnterForeground(_:)` (or `SceneDelegate.sceneWillEnterForeground(_:)` for scene-based applications):
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
If the application uses the background modes supported by iOS, post `Database.resumeNotification` method from each and every background mode callback that may use the database. For example, if your application supports background fetches:
```swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
Suspended databases greatly reduce the odds of `0xDEAD10CC` exception are greatly reduced. If you see one in your crash logs, please open an issue!
In exchange, you will get `SQLITE_INTERRUPT` (9) or `SQLITE_ABORT` (4) errors, with messages "Database is suspended", "Transaction was aborted", or "interrupted", for any attempt at writing in the database when it is suspended.
You can catch those errors:
```swift
do {
try dbPool.write { db in ... }
} catch let error as DatabaseError where error.isInterruptionError {
// Oops, the database is suspended.
// Maybe try again after database is resumed?
}
```
## How to perform cross-process database observation
GRDB [Database Observation] features, as well as [GRDBCombine] and [RxGRDB], are not able to notify database changes performed by other processes.
Whenever you need to notify other processes that the database has been changed, you will have to use a cross-process notification mechanism such as [NSFileCoordinator] or [CFNotificationCenterGetDarwinNotifyCenter].
You can trigger those notifications automatically with [DatabaseRegionObservation]:
```swift
// Notify all changes made to the "player" and "team" database tables
let observation = DatabaseRegionObservation(tracking: Player.all(), Team.all())
let observer = try observation.start(in: dbPool) { (db: Database) in
// Notify other processes
}
// Notify all changes made to the database
let observation = DatabaseRegionObservation(tracking: DatabaseRegion.fullDatabase)
let observer = try observation.start(in: dbPool) { (db: Database) in
// Notify other processes
}
```
[Use a Database Pool]: #use-a-database-pool
[How to limit the `SQLITE_BUSY` error]: #how-to-limit-the-sqlite_busy-error
[How to limit the `0xDEAD10CC` exception]: #how-to-limit-the-0xdead10cc-exception
[How to perform cross-process database observation]: #how-to-perform-cross-process-database-observation
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.19.2](https://www.sqlite.org/changes.html).**
**You can build GRDB with a custom build of [SQLite 3.28.0](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).
@@ -11,13 +11,13 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
**To install GRDB with a custom SQLite build:**
1. Clone the GRDB.swift 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.swift directory]
git checkout v1.2
cd [GRDB directory]
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`.
@@ -60,7 +60,7 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
# !! MODIFY THESE TO MATCH YOUR PROJECT HIERARCHY !!
# The path to the folder containing GRDB.xcodeproj:
# The path to the folder containing GRDBCustom.xcodeproj:
GRDB_SOURCE_PATH="${PROJECT_DIR}/GRDB"
# The path to your custom "SQLiteLib-USER.xcconfig":
@@ -107,11 +107,11 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
Modify the top of `GRDBCustomSQLite-INSTALL.sh` file so that it contains correct paths.
5. Embed the `GRDB.xcodeproj` project in your own project.
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**.
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 `GRDBCustomSQLite.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**:
@@ -120,13 +120,15 @@ GRDB builds SQLite with [swiftlyfalling/SQLiteLib](https://github.com/swiftlyfal
```
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).
Now you can use GRDB with your custom SQLite build:
`AppDelegate` creates, on application startup, a unique instance of [DatabaseQueue](../../README.md#database-queues) available for the whole application.
`AppDatabase` defines the database for the whole application. It uses [DatabaseMigrator](../../README.md#migrations) in order to setup the database schema.
- [Player.swift](GRDBDemoiOS/Player.swift)
`Player` is a [Record](../../README.md#records) type, able to read and write in the database. It conforms to the standard Codable protocol in order to gain all advantages of [Codable Records](../../README.md#codable-records).
**Some parts of GRDB are extensible, so that you can make it better fit your needs.**
This guide is a step-by-step tour of GRDB extensibility, around a few topics:
- **[Add a value type](#add-a-value-type)**
You'll learn how to turn UIColor into a value type that you can store, fetch, and use in your records:
```swift
let rows = try Row.fetchCursor(db, "SELECT name, color FROM clothes")
while let row = try rows.next() {
let name: String = row.value(named: "name")
let color: UIColor = row.value(named: "color") // <-- New! UIColor as value
}
```
- **[Add an SQLite function or operator](#add-an-sqlite-function-or-operator)**
You'll learn how to add support for the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator:
```swift
Books.select(strftime("%Y", Column("publishedDate"))) // <-- New! strftime function
- **[Add a new kind of SQLite expression](#add-a-new-kind-of-sqlite-expression)**
You'll learn how to add support for [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr):
```swift
let jsonString = Column("jsonString")
let request = Books.select(cast(jsonString, as: .blob)) // <-- New! cast function
let rows = try Row.fetchCursor(db, request)
while let row = try rows.next() {
let data = row.dataNoCopy(atIndex: 0)
}
```
- **Extend the query interface requests**
You may need to extend the [query interface requests](../../../#requests) so that their SELECT queries could embed recursive clauses, table joins, etc.
Pull requests are welcome. Open issues if you have questions.
Meanwhile, you can build your own [custom requests](../../../#custom-requests).
- **[Add a custom FTS5 full-text tokenizer](FTS5Tokenizers.md)**
Custom tokenizers can leverage extra full-text features such as synonyms or stop words.
- **Support a new kind of SQL query**
For example, you may need to generate SQL triggers, or create specific kinds of virtual tables.
Pull requests are welcome. Open issues if you have questions.
## Add a Value Type
**All value types adopt the [DatabaseValueConvertible protocol](../../../#custom-value-types).**
```swift
protocol DatabaseValueConvertible {
/// Returns a value that can be stored in the database.
var databaseValue: DatabaseValue { get }
/// Returns a value initialized from databaseValue, if possible.
The `databaseValue` property returns [DatabaseValue](../../../#databasevalue), a type that wraps the five values supported by SQLite: NULL, Int64, Double, String and Data. Since DatabaseValue has no public initializer, use `DatabaseValue.null`, or another type that already adopts the protocol: `1.databaseValue`, `"foo".databaseValue`, etc. Conversion to DatabaseValue *must not* fail.
The `fromDatabaseValue()` factory method returns an instance of your custom type if the databaseValue contains a suitable value. If the databaseValue does not contain a suitable value, such as "foo" for Date, `fromDatabaseValue` *must* return nil (GRDB will interpret this nil result as a conversion error, and react accordingly).
**What does the DatabaseValueConvertible protocol bring to a type like UIColor?**
Well, you will be able to use UIColor like all other [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
- Use UIColor as [statement arguments](../../../#executing-updates):
```swift
try db.execute(
"INSERT INTO clothes (name, color) VALUES (?, ?)",
arguments: ["Shirt", UIColor.red])
```
- UIColor can be [extracted from rows](../../../#column-values):
```swift
let rows = try Row.fetchCursor(db, "SELECT * FROM clothes")
while let row = try rows.next() {
let name: String = row.value(named: "name")
let color: UIColor = row.value(named: "color")
}
```
- UIColor can be [directly fetched](../../../#value-queries):
```swift
let colors = try UIColor.fetchAll(db, "SELECT DISTINCT color FROM clothes") // [UIColor]
guard let data = Data.fromDatabaseValue(databaseValue) else {
return nil
}
// We're looking for an archived object
guard let color = NSKeyedUnarchiver.unarchiveObject(with: data) else {
return nil
}
// The cast function will return nil if the unarchived object doesn't
// have the correct type
return cast(color) // Converts Any to Self?
}
}
```
Use the `cast` utility function when you want *non-final classes* to implement DatabaseValueConvertible. It avoids compiler errors that are not easy to deal with. Note that final classes and value types won't need it.
```swift
// Workaround Swift inconvenience around factories methods of non-final classes
func cast<T, U>(_ value: T) -> U? {
return value as? U
}
```
## Add an SQLite Function or Operator
**When an SQLite [function](https://www.sqlite.org/lang_corefunc.html) or [operator](https://www.sqlite.org/lang_expr.html) is missing from GRDB**, this usually means that there hasn't been a [feature request](http://github.com/groue/GRDB.swift/issues) yet.
But you don't have to wait: you can extend GRDB and the query interface to add support for the missing syntax element (and eventually submit a pull request later).
Let's remind our goal: we'll add the [STRFTIME](https://www.sqlite.org/lang_datefunc.html) function, and the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator.
Their SQL usage is the following:
```sql
-- Publication years of books
SELECT STRFTIME('%Y', publishedOn) FROM books;
-- Books that talk about Moby Dick
SELECT * FROM books WHERE body GLOB '*Moby-Dick*';
`strftime` is a top-level Swift function because this is how GRDB usually imports SQLite functions which do not have matching standard Swift counterpart, like AVG, LEGNTH, SUM. It helps the Swift code looking like SQL when it is relevant.
In the same fashion, we expose the GLOB SQL operator as the `glob` Swift method, just because `value.glob(pattern)` reads like `value GLOB pattern`.
Whenever you import a SQL feature to Swift, you'll have to decide: should you preserve the SQL look and feel, or adopt a well-established swiftism? It's really up to you.
The [STRFTIME](https://www.sqlite.org/lang_datefunc.html) SQL function accepts many arguments. We'll simplify it to `strftime(format, date)`, so that we can write:
SQLSpecificExpressible and SQLExpression are types of the [query interface](../../../#the-query-interface) that you do not usually see. We have moved down one floor, closer to the SQL guts of GRDB. We'll see more new types and protocols below.
The return value is SQLExpression. All GRDB functions and operators that build [query interface expressions](../../../#expressions) return values of this type. It represents actual [SQLite expressions](https://www.sqlite.org/lang_expr.html).
SQLExpression is a protocol, so that you can build your own [custom expressions](#add-a-new-kind-of-sqlite-expression). But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, and here we'll use SQLExpressionFunction that is dedicated to function calls:
return SQLExpressionFunction(.strftime, arguments: format, date)
}
```
The `strftime` function is now complete, ready to be used. We haven't yet described the SQLSpecificExpressible type of the `date` argument:
SQLSpecificExpressible is the protocol for all types that can be turned into a SQL expression, but types like Int, Date, or UIColor that exist outside of GRDB and the query interface. Having `strftime` accept a SQLSpecificExpressible date prevents it from polluting the global space. It is *specific* to GRDB:
You may want to compare it to another protocol, SQLExpressible, which will be described [below](#add-a-new-kind-of-sqlite-expression), when we add support for CAST SQL expressions.
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `strftime` function, it is the SQLSpecificExpressible protocol.
For the [GLOB](https://www.sqlite.org/lang_expr.html#like) operator, we want to define the glob Swift method:
```swift
// Books that talk about Moby Dick
// SELECT * FROM books WHERE body GLOB '*Moby-Dick*'
Books.filter(Column("body").glob("*Moby-Dick*"))
```
This time we can't use the SQLExpressionFunction type, because it can't generate the SQL for a binary operator. Instead, we'll use another [built-in expression](#built-in-expressions), SQLExpressionBinary:
```swift
struct SQLExpressionBinary : SQLExpression {
/// Creates an expression made of two expressions joined with a binary operator.
Now we have to find the signature of our Swift method. The GLOB operator accepts any value on both sides. However, what kind of Swift code should we accept?
```swift
// 1) body GLOB '*Moby-Dick*' -- Yes, of course
Column("body").glob("*Moby-Dick*")
// 2) body GLOB pattern -- Sure, why not?
Column("body").glob(Column("pattern"))
// 3) 'Some Swift String' GLOB pattern - Not sure, but OK
"Some Swift String".glob(Column("pattern"))
// 4) 'Some Swift String' GLOB 'Another Swift String' -- NO
"Some Swift String".glob("Another Swift String")
```
We don't want the form 4, because this is an unacceptable pollution of the Swift global namespace. A good GRDB extension limits its scope to database-related code.
We thus have two overloaded definitions of the `glob` method:
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all expressions, and all [value types](../../../#values) (including String).
SQLSpecificExpressible is a sub protocol of SQLExpressible protocol, restricted to all types that can be turned into a SQL expression, but types like Int, Date, or String that exist outside of GRDB and the query interface.
By extending both, we can define the GLOB operators for any pair that contains at least one type that is specific to GRDB - and leave the global Swift space clean.
The final implementation follows:
```swift
// Add a SQLBinaryOperator just like we add NSNotification.Name since
When you extend GRDB with a new function, method, or operator that generates an [SQL expression](https://www.sqlite.org/lang_expr.html), you have to return a value the adopts the SQLExpression protocol.
We have already seen in our [previous](#strftime) [examples](#glob) two concrete types that generate SQL function calls and binary operators: SQLExpressionFunction and SQLExpressionBinary.
This section of the documentation lists all built-in expressions. Adding a custom SQLExpression type will be documented [below](#add-a-new-kind-of-sqlite-expression).
#### Column and DatabaseValue
The [Column](../../../#the-query-interface) type from the query interface, and [DatabaseValue](../../../#databasevalue), the type that wraps the five values supported by SQLite (NULL, Int64, Double, String and Data) are expressions. They are rather trivial, and it is unlikely that you use them in your GRDB extensions.
#### SQLExpressionLiteral
Use SQLExpressionLiteral when you need to go fast:
You add missing SQLite function names by extending SQLFunctionName:
```swift
extension SQLFunctionName {
/// The `STRFTIME` SQL function
static let strftime = SQLFunctionName("STRFTIME")
}
```
#### The IN Operator
Build a `value IN (...)` expression from any sequence of [values](../../../#values):
```swift
// SQLExpression: id IN (1, 2, 3)
[1,2,3].contains(Column("id"))
// SQLExpression: id NOT IN (1, 2, 3)
![1,2,3].contains(Column("id"))
```
#### The BETWEEN Operator
Build a `value BETWEEN min AND max` expression from Swift ranges:
```swift
// SQLExpression: id BETWEEN 1 AND 10
1...10.contains(Column("id")
```
#### The COUNT Function
Build a `COUNT(...)` expression from the [count](http://groue.github.io/GRDB.swift/docs/1.2/Functions.html) and [count(distinct:)](http://groue.github.io/GRDB.swift/docs/1.2/Functions.html) functions:
```swift
// SQLExpression: COUNT(email)
count(Column("email"))
// SQLExpression: COUNT(DISTINCT email)
count(distinct: Column("email"))
```
#### The COLLATE Operator
Build a `expression COLLATE collation` expression with the `collating` method:
```swift
// SQLExpression: name = 'Arthur' COLLATE NOCASE
Column("name").collating(.nocase) == "Arthur"
```
## Add a New Kind of SQLite Expression
GRDB does not have built-in support for the full range of the SQLite [expression grammar](https://www.sqlite.org/lang_expr.html).
For example, [CAST expressions](https://www.sqlite.org/lang_expr.html#castexpr) are not ready-made. They can be useful, though: a CAST expression can efficiently convert json strings to UTF-8 data blobs for you:
```sql
SELECT CAST(jsonString AS BLOB) FROM books
```
We'll add below a Swift `cast` function:
```swift
let request = Books.select(cast(Column("jsonString"), as: .blob))
let jsonDatas = try Data.fetchAll(db, request) // [Data]
```
`cast` is a top-level Swift function because this is how GRDB usually imports SQLite features which do not have matching standard Swift counterpart. It helps the Swift code looking like SQL when it is relevant. But YMMV.
The signature of the `cast` function is:
```swift
func cast(_ value: SQLExpressible, as type: Database.ColumnType) -> SQLExpression
```
Database.ColumnType is a String-based enumeration of all database column types (.integer, .text, .blob, etc.) You have already used if you have [created tables](../../../#create-tables) using the query interface.
The return type SQLExpression is the type returned by all GRDB functions and operators that build [query interface expressions](../../../#expressions).
SQLExpression is a protocol. But GRDB ships with a variety of [built-in expressions](#built-in-expressions) that are ready-made, so that you generally don't have to write your custom expression type. Here we need something new. So we'll use the most versatile of all, SQLExpressionLiteral:
We haven't yet described the SQLExpressible type of the `value` argument:
SQLExpressible is the protocol for all types that can be turned into a SQL expression. This includes all [value types](../../../#values) (Bool, Int, String, Date, Swift enums, etc.):
```swift
cast("foo", as: .blob) // SQLExpression: CAST('foo' AS BLOB)
cast(Column("name"), as: .blob) // SQLExpression: CAST(name AS BLOB)
```
You may want to compare it to another protocol, SQLSpecificExpressible, which has been described [above](#strftime), when we were adding support for the STRFTIME SQL function.
> :point_up: **Note**: whenever you extend GRDB with a Swift function, method, or operator, you should generally make sure that its signature contains at least one GRDB-specific type. In the `cast` function, it is Database.ColumnType.
**If SQLExpressionLiteral reveals too limited for your purpose**, you may have to implement a new type that adopts the [SQLExpression](http://groue.github.io/GRDB.swift/docs/1.2/Protocols/SQLExpression.html) protocol.
**FetchedRecordsController is a sunsetted GRDB API.**
It is not deprecated. But FetchedRecordsController has known limitations which are not planned to be lifted.
You are advised to use [ValueObservation] instead of FetchedRecordsController.
---
**FetchedRecordsController tracks changes in the results of a request, feeds table views and collection views, and animates cells when the results of the request change.**
It looks and behaves very much like [Core Data's NSFetchedResultsController](https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsController_Class/).
Given a fetch request, and a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](../README.md#record-class) class, a FetchedRecordsController is able to track changes in the results of the fetch request, notify of those changes, and return the results of the request in a form that is suitable for a table view or a collection view, with one cell per fetched record.
- [Creating the Fetched Records Controller](#creating-the-fetched-records-controller)
When you initialize a fetched records controller, you provide the following mandatory information:
- A [database connection](../README.md#database-connections)
- The type of the fetched records. It must be a type that adopts the [FetchableRecord] protocol, such as a subclass of the [Record](../README.md#record-class) class
- A fetch request
```swift
classPlayer:Record{...}
letdbQueue=DatabaseQueue(...)//orDatabasePool
//UsingaRequestfromtheQueryInterface:
letcontroller=FetchedRecordsController(
dbQueue,
request:Player.order(Column("name")))
//UsingSQL,andeventualarguments:
letcontroller=FetchedRecordsController<Player>(
dbQueue,
sql:"SELECT * FROM player ORDER BY name WHERE countryCode = ?",
arguments:["FR"])
```
The fetch request can involve several database tables. The fetched records controller will only track changes in the columns and tables used by the fetch request.
```swift
letcontroller=FetchedRecordsController<Author>(
dbQueue,
sql:"""
SELECT author.name, COUNT(book.id) AS bookCount
FROM author
LEFT JOIN book ON book.authorId = author.id
GROUP BY author.id
ORDER BY author.name
""")
```
After creating an instance, you invoke `performFetch()` to actually execute
the fetch.
```swift
trycontroller.performFetch()
```
## Responding to Changes
In general, FetchedRecordsController is designed to respond to changes at *the database layer*, by [notifying](#the-changes-notifications) when *database rows* change location or values.
Changes are not reflected until they are applied in the database by a successful [transaction](../README.md#transactions-and-savepoints):
When you apply several changes to the database, you should group them in a single explicit transaction. The controller will then notify of all changes together.
## The Changes Notifications
An instance of FetchedRecordsController notifies that the controller’s fetched records have been changed by the mean of *callbacks*:
```swift
letcontroller=tryFetchedRecordsController(...)
controller.trackChanges(
//controller'srecordsareabouttochange:
willChange:{controllerin...},
//notificationofindividualrecordchanges:
onChange:{(controller,record,change)in...},
//controller'srecordshavechanged:
didChange:{controllerin...})
trycontroller.performFetch()
```
See [Implementing Table View Updates](#implementing-table-view-updates) for more detail on table view updates.
**All callbacks are optional.** When you only need to grab the latest results, you can omit the `didChange` argument name:
```swift
controller.trackChanges{controllerin
letnewPlayers=controller.fetchedRecords//[Player]
}
```
> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information.
Callbacks have the fetched record controller itself as an argument: use it in order to avoid memory leaks:
```swift
//BAD:memoryleak
controller.trackChanges{_in
letnewPlayers=controller.fetchedRecords
}
//GOOD
controller.trackChanges{controllerin
letnewPlayers=controller.fetchedRecords
}
```
**Callbacks are invoked asynchronously.** See [FetchedRecordsController Concurrency](#fetchedrecordscontroller-concurrency) for more information.
**Values fetched from inside callbacks may be inconsistent with the controller's records.** This is because after database has changed, and before the controller had the opportunity to invoke callbacks in the main thread, other database changes can happen.
To avoid inconsistencies, provide a `fetchAlongside` argument to the `trackChanges` method, as below:
Whenever the fetched records controller can not look for changes after a transaction has potentially modified the tracked request, an error handler is called. The request observation is not stopped, though: future transactions may successfully be handled, and the notified changes will then be based on the last successful fetch.
```swift
controller.trackErrors{(controller,error)in
print("Missed a transaction because \(error)")
}
```
## Modifying the Fetch Request
You can change a fetched records controller's fetch request or SQL query.
The [notification callbacks](#the-changes-notifications) are notified of eventual changes if the new request fetches a different set of records.
> :point_up: **Note**: This behavior differs from Core Data's NSFetchedResultsController, which does not notify of record changes when the fetch request is replaced.
**Change callbacks are invoked asynchronously.** This means that modifying the request from the main thread does *not* immediately triggers callbacks. When you need to take immediate action, force the controller to refresh immediately with its `performFetch` method. In this case, changes callbacks are *not* called:
FetchedRecordsController let you feed table and collection views, and keep them up-to-date with the database content.
For nice animated updates, a fetched records controller needs to recognize identical records between two different result sets. When records adopt the [TableRecord] protocol, they are automatically compared according to their primary key:
```swift
classPlayer:TableRecord{...}
letcontroller=FetchedRecordsController(
dbQueue,
request:Player.all())
```
For other types, the fetched records controller needs you to be more explicit:
> :point_up: **Note**: In its current state, FetchedRecordsController does not support grouping table view rows into custom sections: it generates a unique section.
### Implementing Table View Updates
When changes in the fetched records should reload the whole table view, you can simply tell so:
```swift
controller.trackChanges{[unownedself]_in
self.tableView.reloadData()
}
```
Yet, FetchedRecordsController can notify that the controller’s fetched records have been changed due to some add, remove, move, or update operations, and help applying animated changes to a UITableView.
#### Typical Table View Updates
For animated table view updates, use the `willChange` and `didChange` callbacks to bracket events provided by the fetched records controller, as illustrated in the following example:
> :warning: **Warning**: notification of individual record changes (the `onChange` callback) has FetchedRecordsController use a diffing algorithm that has a high complexity, a high memory consumption, and is thus **not suited for large result sets**. One hundred rows is probably OK, but one thousand is probably not. If your application experiences problems with large lists, see [Issue 263](https://github.com/groue/GRDB.swift/issues/263) for more information.
>
> :point_up: **Note**: our sample code above uses `unowned` references to the table view controller. This is a safe pattern as long as the table view controller owns the fetched records controller, and is deallocated from the main thread (this is usually the case). In other situations, prefer weak references.
## FetchedRecordsController Concurrency
**A fetched records controller *can not* be used from any thread.**
When the database itself can be read and modified from [any thread](../README.md#database-connections), fetched records controllers **must** be used from the main thread. Record changes are also [notified](#the-changes-notifications) on the main thread.
**Change callbacks are invoked asynchronously.** This means that changes made from the main thread are *not* immediately notified. When you need to take immediate action, force the controller to refresh immediately with its `performFetch` method. In this case, changes callbacks are *not* called:
```swift
//Changedatabaseonthemainthread:
trydbQueue.write{dbin
tryPlayer(...).insert(db)
}
//Herecallbackshavenotbeencalledyet.
//Youcancancelthem,andrefreshrecordsimmediately:
trycontroller.performFetch()
```
> :point_up: **Note**: when the main thread does not fit your needs, give a serial dispatch queue to the controller initializer: the controller must then be used from this queue, and record changes are notified on this queue as well.
>
> ```swift
> let queue = DispatchQueue()
> queue.async {
> let controller = try FetchedRecordsController(..., queue: queue)
- **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. FTS4 only supports content compression.
- **The location of the indexed text in your database schema.** Only FTS4 and FTS5 support "contentless" and "external content" tables.
- **The SQLite library integrated in your application.** The version of SQLite that ships with iOS, macOS, tvOS and watchOS supports FTS3 and FTS4 out of the box, but not always FTS5. To use FTS5, see [Enabling FTS5 Support](#enabling-fts5-support).
- See [FST3 vs. FTS4](https://www.sqlite.org/fts3.html#differences_between_fts3_and_fts4) and [FTS5 vs. FTS3/4](https://www.sqlite.org/fts5.html#appendix_a) for more differences.
> :point_up: **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: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 defining 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.
## FTS3Pattern
**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 validating patterns, and building 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?(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 three 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 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 = FTS3Pattern(matchingAnyTokenIn: query)
// Matches documents that contain both "SQLite" and "database"
let pattern = FTS3Pattern(matchingAllTokensIn: 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 are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html):
```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(Column("content").match(pattern)).fetchAll(db)
```
## Enabling FTS5 Support
When the FTS3 and FTS4 full-text engines don't suit your needs, you may want to use FTS5. See [Choosing the Full-Text Engine](#choosing-the-full-text-engine) to help you make a decision.
The version of SQLite that ships with iOS, macOS, tvOS and watchOS does not always support the FTS5 engine. To enable FTS5 support, you'll need to install GRDB with one of those installation techniques:
1. Use the GRDB.swift CocoaPod with a custom compilation option, as below. It uses the system SQLite, which is compiled with FTS5 support, but only on iOS 11.4+ / macOS 10.13+ / tvOS 11.4+ / watchOS 4.3+:
```ruby
pod 'GRDB.swift'
platform :ios, '11.4' # or above
post_install do |installer|
installer.pods_project.targets.select { |target| target.name == "GRDB.swift" }.each do |target|
> :warning: **Warning**: make sure you use the right platform version! You will get runtime errors on devices with a lower version.
> :point_up: **Note**: there used to be a GRDBPlus CocoaPod with pre-enabled FTS5 support. This CocoaPod is deprecated: please switch to the above technique.
2. Use the GRDB.swift/SQLCipher CocoaPod subspec (see [encryption](../README.md#encryption)):
```ruby
pod 'GRDB.swift/SQLCipher'
```
3. Use a [custom SQLite build] and activate the `SQLITE_ENABLE_FTS5` compilation option.
## 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: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 defining 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.
## 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 validating patterns, and building 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 both "SQLite" and "database"
let pattern = FTS5Pattern(matchingAllTokensIn: 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 are regular [values](../README.md#values). You can use them as query [arguments](http://groue.github.io/GRDB.swift/docs/4.5/Structs/StatementArguments.html):
```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
let documents = try Document.matching(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 can not 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")
}
```
The eventual 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 the mean 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 insertion, 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: **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 in the same time 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.**
However these tables don't have any explicit primary key. Instead, they use the [implicit rowid primary key](../README.md#the-implicit-rowid-primary-key): a special hidden column named `rowid`.
You will have to [expose this hidden column](../README.md#exposing-the-rowid-column) in order to fetch, delete, and update full-text records by primary key.
## 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/reference/swift/string/1407210-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/reference/swift/string/1407834-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/reference/swift/string/1643133-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.
**This guide aims at helping you upgrading your applications from GRDB 4 to GRDB 5.**
- [Preparing the Migration to GRDB 5](#preparing-the-migration-to-grdb-5)
- [New requirements](#new-requirements)
- [ValueObservation](#valueobservation)
- [Other Changes](#other-changes)
## Preparing the Migration to GRDB 5
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.2+** (was Swift 4.2+)
- **Xcode 11.4+** (was Xcode 10.0+)
- iOS 9.0+ (unchanged)
- **macOS 10.10+** (was macOS 10.9+)
- tvOS 9.0+ (unchanged)
- watchOS 2.0+ (unchanged)
## ValueObservation
[ValueObservation] is the database observation tool that tracks changes in database values. It has quite changed in GRDB 5.
Those changes have the vanilla GRDB, [GRDBCombine], and [RxGRDB], offer a common API, and a common behavior. This greatly helps choosing or switching 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!
If the tracked value is computed from several database requests that are not always the same, make sure you use the `trackingVaryingRegion` method, as below. See [Observing a Varying Database Region] for more information.
Finally, ValueObservation used to let application define custom "reducers" based on a protocol name 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 quite impact 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 be granted with 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 = 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>GRDBCombine 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 eventual 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 GRDBCombine 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
// BEFORE: GRDB 4
let playerCountObservation = ValueObservation.tracking(Player.fetchCount)
let bestPlayersObservation = ValueObservation.tracking(Player
As is previous versions of GRDB, do not use the `combineLatest` operators of Combine or RxSwift in order to combine several ValueObservation. You would lose all guarantees of [data consistency](https://en.wikipedia.org/wiki/Consistency_(database_systems)).
## Other Changes
1. [Batch updates] used to rely of the `<-` operator. This operator has been removed. Use the `set(to:)` method instead:
2. [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")))
```
3. If you happen to implement custom fetch requests with the `FetchRequest` protocol, you now have to define the `makePreparedRequest(_:forSingleResult:)` method:
4. 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
```
5. Importing the `GRDB` module grants access to the [SQLite C interface](https://www.sqlite.org/c3ref/intro.html). You don't need any longer 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())
This guide aims at helping you leverage the best of GRDB [records] and [associations].
Since GRDB sits right between low-level libraries like SQLite itself or [FMDB], and high-level ORM like [Core Data] or [Realm], you may face questions when designing the model layer of your application.
To support this guide, we'll design a simple library application that lets the user crawl through books and their authors.
- [Trust SQLite More Than Yourself]
- [Persistable Record Types are Responsible for Their Tables]
- [Define Record Requests]
- [Compose Records]
- [How to Design Database Managers]
- [Observe the Database and Refetch when Needed]
## Trust SQLite More Than Yourself
It is important to put things in the right order. An SQLite database stored on one of your user's device is more important than the Swift code that accesses it. When a user installs a new version of your application, all the code may change, but the database remains the same.
This is why we recommend defining a **robust database schema** even before playing with record types.
SQLite is a battle-tested database. Even if you don't know it well, and aren't familiar with the SQL language, you are able to take profit from its solid foundation. It is very difficult to corrupt an SQLite database file. And it can make sure that only valid information is persisted on disk.
This is important because we developers write bugs, and some of them will ship in the wild, affecting the users of our applications. But SQLite will prevent many of those bugs from corrupting our precious users' data.
For example, if we were to define a [migration] that sets up our library database, made of books and their authors, we could write:
```swift
varmigrator=DatabaseMigrator()
migrator.registerMigration("createLibrary"){dbin
trydb.create(table:"author"){tin//(1)
t.autoIncrementedPrimaryKey("id")//(2)
t.column("name",.text).notNull()//(3)
t.column("country",.text)//(4)
}
trydb.create(table:"book"){tin
t.autoIncrementedPrimaryKey("id")
t.column("title",.text).notNull()//(5)
t.column("authorId",.integer)//(6)
.notNull()//(7)
.indexed()//(8)
.references("author",onDelete:.cascade)//(9)
}
}
trymigrator.migrate(dbQueue)
```
1. Our database table names follow the [recommended convention]: they are English, singular, and camelCased. They look like Swift identifiers: `author`, `book`, `postalAddress`, `httpRequest`.
2. Each author has a unique id.
3. An author must have a name.
4. The country of an author is not always known.
5. A book must have a title.
6. The `book.authorId` column is used to link a book to the author it belongs to.
7. The `book.authorId` column is not null so that SQLite guarantees that all books have an author.
8. The `book.authorId` column is indexed in order to ease the selection of an author's books.
9. We define a foreign key from `book.authorId` column to `authors.id`, so that SQLite guarantees that no book can refer to a missing author. On top of that, the `onDelete: .cascade` option has SQLite automatically delete all of an author's books when that author is deleted. See [Foreign Key Actions] for more information.
Thanks to this database schema, you can be confident that no matter how wrong our application goes, it will always process *consistent data*. Even after a hard crash, application will always find the author of any book, all books will have a non-nil title, etc.
> :bulb: **Tip**: Don't look at your local SQLite database as you look at the JSON you load from a remote server. You can't control the JSON, its format and content: your application must defend itself against wacky servers. But you can control the database. Put the database on your side, make it trustable. Learn about relational databases, and how they can help you guarantee the quality of your application data. Put as much energy as you can in the proper definition of your database schema.
>
> :bulb: **Tip**: Plan early for future versions of your application, and use [migrations].
>
> :bulb: **Tip**: In the definition of your migrations, define tables and their columns with **strings**:
>
> ```swift
> migrator.registerMigration("createLibrary") { db in
> // RECOMMENDED
> try db.create(table: "author") { t in
> t.autoIncrementedPrimaryKey("id")
> ...
> }
>
> // NOT RECOMMENDED
> try db.create(table: Author.databaseTableName) { t in
> By using strings, you make sure that you will not have to change the Swift code of your migrations in the future. Even if author columns eventually change. Even if the Author type eventually gets replaced with another type. Even when your startup eventually pivots and starts selling pet food. A good migration that never changes is easy to test once and for good. A good migration that never changes will run smoothly on all devices in the wild, even if a user upgrades straight from version 1.0 to version 5.0 of your application.
>
> So make sure that migrations don't use application types and values: migrations should talk to the database, only to the database, and use the database language: **strings**.
## Persistable Record Types are Responsible for Their Tables
Define one record type per database table, and make it adopt a [PersistableRecord] protocol.
In this sample code, we'll use Codable structs, but there are [other ways](../README.md#examples-of-record-definitions) to define records.
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:
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.
## Define Record Requests
Now that we have record types that are able to read and write in the database, we'd like to put them to good use.
> :bulb: **Tip**: Define an enumeration of columns that you will use in order to filter, sort, etc.
When your record type is a [Codable Record], derive columns from the [CodingKeys] enum:
```swift
//Foracodablerecord
extensionAuthor{
//DefinedatabasecolumnsfromCodingKeys
enumColumns{
staticletid=Column(CodingKeys.id)
staticletname=Column(CodingKeys.name)
staticletcountry=Column(CodingKeys.country)
}
}
```
Otherwise, declare a plain String enum that conforms to the ColumnExpression protocol:
```swift
//Foranon-codablerecord
extensionAuthor{
//Definedatabasecolumnsasanenum
enumColumns:String,ColumnExpression{
caseid,name,country
}
}
```
> :bulb: **Tip**: Define commonly used requests in a constrained extension of the `DerivableRequest` protocol.
The `DerivableRequest` protocol generally lets you filter, sort, and join or include associations (we'll talk about associations in the [Compose Records] chapter below).
Those methods defined on the `DerivableRequest` protocol hide intimate database details. They allow you to compose database requests in a fluent style:
```swift
trydbQueue.read{dbin
letsortedAuthors:[Author]=tryAuthor.all()
.orderByName()
.fetchAll(db)
letfrenchAuthors:[Author]=tryAuthor.all()
.filter(country:"France")
.fetchAll(db)
letsortedSpanishAuthors:[Author]=tryAuthor.all()
.filter(country:"Spain")
.orderByName()
.fetchAll(db)
}
```
Those customized request methods are also available on record associations, because associations conform to the `DerivableRequest` protocol:
Not *every requests* can be expressed on `DerivableRequest`. For example, [Association Aggregates] are out of scope. When this happens, define your requests in a constrained extension to `QueryInterfaceRequest`:
Those requests defined on `QueryInterfaceRequest` still compose fluently:
```swift
trydbQueue.read{dbin
letsortedFrenchAuthorsHavingBooks=tryAuthor.all()
.filter(country:"France")
.havingBooks()//<-
.orderByName()
.fetchAll(db)
}
```
Finally, when it happens that a request only makes sense when defined on the Record type itself, just go ahead and define a static method or property of your Record type:
```swift
extensionMySingletonRecord{
///Theoneanyonlyrecordstoredinthedatabase
staticletshared=all().limit(1)
}
letsingleton=trydbQueue.read{db
tryMySingletonRecord.shared.fetchOne(db)
}
```
## Compose Records
We'd like to navigate from books to authors and vice-versa: we may want to know an author's books, or a book's author.
GRDB can help you do this with [associations]. In our case, each author **has many** books, and each book **belongs to** its author. Here is how you define those associations:
```swift
extensionAuthor{
staticletbooks=hasMany(Book.self)
}
extensionBook{
staticletauthor=belongsTo(Author.self)
}
```
Thanks to this setup, you can fetch associated records, or compute aggregated values from associated records. For example:
As in the sample code above, requests which feed from several associated records will often have you define extra record types, such as `AuthorInfo` and `Authorship`. Those extra record types are designed to be able to decode database requests. The names and types of their properties follow the conventions defined by [associations]. Make them conform to the Decodable and FetchableRecord protocols so that they can decode database rows in a breeze.
Unlike the primitive persistable record types `Author` and `Book`, those records can not write in the database. They are simple data types, passive views on the database content. Remember, only [Persistable Record Types are Responsible for Their Tables].
> :question: **Note**: The example `AuthorInfo` and `Authorship` types above may look superfluous to you. After all, other ORMs out there are able to navigate in complex graphs of records without much fuss, aren't they?
>
> That is because other ORMs perform lazy loading:
>
> ```ruby
> # Ruby's Active Record
> author = Author.find(123) # fetch author
> book_count = author.books.count # lazily counts books on demand
> ```
>
> GRDB does not perform lazy loading. Lazy loading either requires records to be *managed* (as in [Core Data] and [Realm]), or that all data processing happens in a *single function* (think of an HTTP request handled with a web-oriented ORM like [Active Record] and [Django]). The underlying issue is *data consistency*: you always want your memory objects to accurately represent your application data, without any glitch, ever. This involves the subtle database concept of [isolation] against concurrent changes. In a GUI application, this can't be achieved without a very complex record management, and non-trivial pain points for the application developer.
>
> This is why GRDB has removed lazy loading from the list of desirable features. Instead, it provides the tooling needed to fetch data, even complex ones, in a single and safe stroke. See the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more information.
Granted with primitive and derived record types, your application will load the data it needs, at the moment it needs it, as below:
1. Prepare the application screen that lists all authors:
```swift
let authors: [Author] = try dbQueue.read { db in
try Author.all().orderByName().fetchAll(db)
}
```
2. Prepare the application screen that displays an author and her books:
```swift
struct AuthorInfo: Codable, FetchableRecord {
var author: Author
var books: [Book]
}
let authorId = 123
let authorInfo: AuthorInfo? = try dbQueue.read { db in
let request = Author
.filter(key: authorId)
.including(all: Author.books)
return try AuthorInfo.fetchOne(db, request)
}
```
3. Prepare the application screen that displays a book information:
```swift
struct BookInfo: Decodable, FetchableRecord {
var book: Book
var author: Author
}
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
let request = Book
.filter(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 primitive record types linked by associations. Fetch the data your application needs, at the moment it needs it, no more, no less.
A last extension on your record types will further help navigation from records to associated ones:
```swift
extension Author {
/// The request for the author's books
var books: QueryInterfaceRequest<Book> {
request(for: Author.books)
}
}
extension Book {
/// The request for the author of the book
var author: QueryInterfaceRequest<Author> {
request(for: Book.author)
}
}
```
Those properties provide an alternative way to feed our application:
1. Prepare the application screen that displays an author and her books:
```swift
struct AuthorInfo {
var author: Author
var books: [Book]
}
let authorId = 123
let authorInfo: AuthorInfo? = try dbQueue.read { db in
guard let author = try Author.fetchOne(db, key: authorId) else {
return nil
}
let books = try author.books.fetchAll(db)
return AuthorInfo(
author: author,
books: books)
}
```
2. Prepare the application screen that displays a book information:
```swift
struct BookInfo {
var book: Book
var author: Author
}
let bookId = 123
let bookInfo: BookInfo? = try dbQueue.read { db in
guard let book = try Book.fetchOne(db, key: bookId) else {
return nil
}
guard let author = try book.author.fetchOne(db) else {
return nil
}
return BookInfo(book: book, author: author)
}
```
## How to Design Database Managers
Many developpers want to hide GRDB database queues and pools inside "database managers":
```swift
// LibraryManager grants access to the library database.
class LibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
}
```
> :bulb: **Tip**: Don't let your database managers create their own databases. Instead, give them a database created by, say, the ApplicationDelegate. This will allow you to efficiently test the database manager with an in-memory database, for example.
Design your database managers with the [GRDB concurrency rules] in mind.
Practically, let's start with a naive example, and gradually improve it:
```swift
// A naive manager that we will improve
class NaiveLibraryManager {
private let dbQueue: DatabaseQueue
init(dbQueue: DatabaseQueue) {
self.dbQueue = dbQueue
}
func author(id: Int64) -> Author? {
do {
return try dbQueue.read { db in
try Author.fetchOne(db, key: id)
}
} catch {
return nil
}
}
func book(id: Int64) -> Book? {
do {
return try dbQueue.read { db in
try Book.fetchOne(db, key: id)
}
} catch {
return nil
}
}
func books(writtenBy author: Author) -> [Book] {
do {
return try dbQueue.read { db in
try author.books.fetchAll(db)
}
} catch {
return []
}
}
}
```
**This manager can be improved in two ways.**
- [Embrace Errors]
- [Thread-Safety is also an Application Concern]
### Embrace Errors
Have database managers throw database errors instead of catching them.
Consider Apple's [CNContactStore](https://developer.apple.com/documentation/contacts/cncontactstore), for example. Does it hide errors when you fetch or save address book contacts? No it does not. Keychain, Media assets, File system, Core Data? No they do not hide errors either. Follow the practices of Apple engineers: do not hide errors :muscle:
Exposing errors will help you building your application:
- You will be able to inspect errors during development, and fix bugs. `do { ... } catch { print(error) }` will save you hours of clueless questioning.
- You will be able to opt in for advanced OS features like [data protection].
> :bulb: **Tip**: Don't hide database errors. Let the application handle them, because only application can decide how to handle them.
This gives the improved manager below. And it has less code, which means less bugs :bowtie:
Now, let's make our database manager **thread-safe**.
This one is more subtle. In order to understand what is wrong in our naive manager, one has to consider how it is used by the application.
For example, in the screen that displays an author and her books, we would write:
```swift
let authorId = 123
if let author = libraryManager.author(id: authorId) {
let books = libraryManager.books(writtenBy: author)
// Use author and books
}
```
This code is not thread-safe, because other application threads may have modified the database between the two database accesses. You may end up with an author without any book, and this sure does not make a pretty application screen.
Such bugs are uneasy to reproduce. Sometimes your application will refresh the library content from the network, and delete an author right at the wrong time. The more users your application has, the more users will see weird screens. And of course, you'll be bitten right on the day of the demo in front of the boss.
Fortunately, GRDB has all the tools you need to prevent such nasty data races:
> :bulb: **Tip**: Make sure you fetch all the data your application needs at a given moment of time, in a **single database read**.
guard let author = try Author.fetchOne(db, key: authorId) else {
return nil
}
let books = try author.books.fetchAll(db)
return AuthorInfo(author: author, books: books)
}
}
}
```
The `AuthorListItem`, `BookInfo`, `AuthorInfo` types returned by the manager are designed to feed your views.
When a new screen is added to your application, and you want to make sure it displays **consistent data** free from any data race, make sure you update the manager if needed. The rule is very simple: consumed data must come from a **single** database access method (`dbQueue.read`, `write`, etc.), or [ValueObservation].
In other words: since GRDB is an unmanaged ORM, some amount of management must be imported into your application in order to make it fully thread-safe.
> :question: **Note**: Wrapping several fetches in a single `read` method may look like an inconvenience to you. After all, other ORMs don't require that much ceremony:
>
> ```ruby
> # Ruby's Active Record
> book = Book.find(123) # fetch book
> author = book.author # fetch author
> # use book and author
> ```
>
> The problem is that it is very hard to guarantee that you will surely fetch an author after you have fetched a book, despite the constraints of the database schema. One has to perform subsequent fetches in the proper [isolation] level, so that eventual concurrent writes that modify the database are unable to mess with subsequent requests.
>
> This isolation can be achieved with record management, as in [Core Data] or [Realm], that target long-running multi-threaded applications. On the other side, most web-oriented ORMs rely on short-lived database transactions, so that each HTTP request can be processed independently of others.
>
> GRDB is not a managed ORM. It thus has to use the same isolation techniques as web-oriented ORMs. But unlike web-oriented ORMs, GRDB can't provide implicit isolation: the application must decide when it wants to safely read information in the database, and this decision is made explicit, in your application code, with database access methods such as `dbQueue.read`.
>
> See the [Concurrency Guide] for detailed information, and the "Solving Problems" chapter of [Why Adopt GRDB?](WhyAdoptGRDB.md#solving-problems) for more rationale.
## Observe the Database and Refetch when Needed
We have seen above that the primitive Author and Book record types are [responsible](#persistable-record-types-are-responsible-for-their-tables) for their own database tables. Later we built [requests](#define-record-requests) and [composed](#compose-records) records into more complex ones such as BookInfo or AuthorInfo. We have shown how [database managers](#how-to-design-database-managers) should expose database content to the rest of the application.
Database content which has been fetched into memory eventually becomes obsoleted, as the application modifies the database content.
It is up to the application to decide how long it should keep fetched information in memory. Very often though, the application will want to keep memory information synchronized with the database content.
This synchronization is not automatic with GRDB: records do not "auto-update". That is because applications do not always want this feature, and because it is difficult to write correct multi-threaded applications when values can change in unexpected ways.
Instead, have a look at [Database Observation]:
> :bulb: **Tip**: [ValueObservation] performs automated tracking of database changes.
>
> :bulb: **Tip**: [GRDBCombine] performs automated tracking of database changes, in the [Combine](https://developer.apple.com/documentation/combine) way.
>
> :bulb: **Tip**: [RxGRDB] performs automated tracking of database changes, in the [RxSwift](https://github.com/ReactiveX/RxSwift) way.
>
> :bulb: **Tip**: [TransactionObserver] provides low-level database observation, for your most advanced needs.
>
> :bulb: **Tip**: Don't try to write complex methods that both modify the database and the values in memory at the same time. Instead, modify the database with plain record types, and rely on database observation for automatically refreshing values, even complex ones.
Loaded 100 of 627 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.