BREAKING: Throwing FetchableRecord.init(row:)

This commit is contained in:
Gwendal Roué authored and Gwendal Roué committed 2022-08-21 21:22:34 +02:00
1 parent 927fc21f00
commit 895964de16
38 files changed
+264 -684

No files matched your search

+1
View File
@@ -102,6 +102,7 @@ GRDB adheres to [Semantic Versioning](https://semver.org/), with one exception:
- **Breaking**: The `selectID()` method is replaced with `selectPrimaryKey(as:)`.
- **Breaking**: `Cursor.isEmpty` is now a throwing property, instead of a method.
- **Breaking**: The `Record.copy()` method was removed, without replacement.
- **Breaking**: The `FetchableRecord.init(row:)` initializer can now throw errors.
- **New**: Request protocols and cursors now define primary associated types, enabled by [SE-0346](https://github.com/apple/swift-evolution/blob/main/proposals/0346-light-weight-same-type-syntax.md).
- **New**: You can append the contents of a cursor to a collection with `RangeReplaceableCollection.append(contentsOf:)`.
- **New**: `ValueObservation.map` now accepts a throwing closure argument.
+4 -4
View File
@@ -2165,8 +2165,8 @@ struct BookInfo: FetchableRecord {
var country: Country?
var coverImage: CoverImage?
init(row: Row) {
book = Book(row: row)
init(row: Row) throws {
book = try Book(row: row)
author = row["author"]
country = row["country"]
coverImage = row["coverImage"]
@@ -2200,8 +2200,8 @@ struct AuthorInfo: FetchableRecord {
var author: Author
var books: [Book]
init(row: Row) {
author = Author(row: row)
init(row: Row) throws {
author = try Author(row: row)
books = row["books"]
}
}
+57
View File
@@ -6,6 +6,7 @@ Migrating From GRDB 5 to GRDB 6
- [Preparing the Migration to GRDB 6](#preparing-the-migration-to-grdb-6)
- [New requirements](#new-requirements)
- [Primary Associated Types](#primary-associated-types)
- [Record Changes](#record-changes)
- [Other Changes](#other-changes)
@@ -42,6 +43,62 @@ Request protocols now come with a primary associated type, enabled by [SE-0346](
The `Cursor` protocol has also gained a primary associated type (the type of its elements).
## Record Changes
The record protocols have been refactored. We tried to keep the amount of modifications to your existing code as small as possible, but some changes could not be avoided.
- **The `FetchableRecord.init(row:)` initializer can now throw errors.**
```diff
-let player = Player(row: row)
+let player = try Player(row: row)
```
Decodable records that derive their `FetchableRecord` implementation from the standard `Decodable` protocol now throw errors when they find unexpected database values (they used to crash in GRDB 5).
If you subclass the `Record` type, you have to update your override of `init(row:)`:
```diff
class Player: Record {
- required init(row: Row) {
+ required init(row: Row) throws {
self.id = row["id"]
self.name = row["name"]
- super.init(row: row)
+ try super.init(row: row)
}
}
```
In record types that do not derive their `FetchableRecord.init(row:)` implementation from the standard `Decodable` protocol, you are responsible for throwing decoding errors, as in the sample code below:
<details>
<summary>Handling untrusted input</summary>
For example:
```swift
struct LogEntry: FetchableRecord {
var date: Date
init(row: Row) throws {
let dbValue: DatabaseValue = row["date"]
if dbValue.isNull {
// Handle NULL
throw ...
} else if let date = Date.fromDatabaseValue(dbValue) {
self.date = date
} else {
// Handle invalid date
throw ...
}
}
}
```
</details>
## Other Changes
- The initializer of in-memory databases can now throw errors:
@@ -1,469 +0,0 @@
//: # Customized Decoding of Database Rows
//:
//: To run this playground:
//:
//: - Open GRDB.xcworkspace
//: - Select the GRDBOSX scheme: menu Product > Scheme > GRDBOSX
//: - Build: menu Product > Build
//: - Select the playground in the Playgrounds Group
//: - Run the playground
import GRDB
//: This playground demonstrates how one can implement **customized decoding of
//: database rows**.
//:
//: Customized row decoding allows you to go beyond the built-in support for
//: requests of raw rows, values, or types that adopt the
//: FetchableRecord protocol.
//:
//: For example:
//:
//: - Your application needs polymorphic row decoding: it decodes some class or
//: another, depending on the values contained in a database row.
//:
//: - Your application needs to decode rows with a context: each decoded value
//: should be initialized with some extra value that does not come from
//: the database.
//:
//: - Your application needs a record type that supports untrusted databases,
//: and may fail at decoding database rows (throw an error when a row contains
//: invalid values).
//:
//: None of those use cases can be handled by the built-in `FetchableRecord`
//: protocol and its `init(row:)` initializer. They need *customized
//: row decoding*.
//:
//: ## An Example: Polymorphic Decoding
//:
//: In this playground, we will provide some sample code that performs
//: polymorphic row decoding. Given a base class, `Base`, and two subclasses
//: `Foo` and `Bar`, we'd like to fetch Foo or Bar instances, depending on the
//: value found in the `type` column of the `base` database table.
//:
//: From this sample code, we hope that you will be able to derive your own
//: customized decoding.
//:
//: Everything starts from our class hierarchy:
class Base {
var description: String { "Base" }
init() { }
}
class Foo: Base {
var name: String
override var description: String { "Foo: \(name)" }
init(name: String) {
self.name = name
super.init()
}
}
class Bar: Base {
var score: Int
override var description: String { "Bar: \(score)" }
init(score: Int) {
self.score = score
super.init()
}
}
//: We need a database, a table, and a few values so that we can do a real demo:
// An in-memory database is good enough
let dbQueue = try DatabaseQueue()
try dbQueue.write { db in
// Database table
try db.create(table: "base") { t in
t.column("type", .text).notNull() // Contains "Foo" or "Bar"
t.column("fooName", .text) // Contains a Foo's name
t.column("barScore", .integer) // Contains a Bar's score
}
// Demo values: two Foo and one Bar
try db.execute(
sql: """
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
INSERT INTO base (type, fooName, barScore) VALUES (?, ?, ?);
""",
arguments: [
"Foo", "Arthur", nil,
"Bar", nil, 100,
"Foo", "Barbara", nil,
])
}
//: We also need a method that decodes database rows into `Foo` or `Bar`
//: instances: let's call it `Base.decode(row:)`:
extension Base {
static func decode(row: Row) -> Base {
switch row["type"] as String {
case "Foo":
return Foo(name: row["fooName"])
case "Bar":
return Bar(score: row["barScore"])
case let type:
fatalError("Unknown Base type: \(type)")
}
}
}
//: Now we are able to express the kind of request we'd like to write. For
//: example, we could fetch all Base values from the database:
//:
//: try dbQueue.read { db in
//: // An array [Base] that contains Foo and Bar instances
//: let bases = try Base.fetchAll(db)
//: }
//:
//: But so far, we have a compiler error:
// Compiler error: Type 'Base' has no member 'fetchAll'
//try dbQueue.read { db in
// let bases = try Base.fetchAll(db)
//}
//: We'll see that this goal can be achieved by declaring a protocol, writing a
//: few extensions that guarantee the most efficient use of GRDB, and have the
//: Base class adopt this protocol.
//:
//: ### Keep It Simple, Stupid!
//:
//: But first, let's see how polymorphic decoding can be done as simply as
//: possible. After all, it is useless to design a full-fledged protocol unless
//: we need to use this protocol several times, or write code that is as
//: streamlined as possible.
//:
//: Can we fetch Foo and Bar values from an SQL request? Sure:
try dbQueue.read { db in
print("> KISS: Fetch from SQL")
let rows = try Row.fetchAll(db, sql: "SELECT * FROM base") // Fetch database rows
let bases = rows.map { row in // Decode database rows
Base.decode(row: row)
}
for base in bases { // Use fetched values
print(base.description)
}
}
//: Can we have GRDB generate SQL for us? Sure, we just need to adopt the
//: `TableRecord` protocol:
extension Base: TableRecord {
static let databaseTableName = "base"
}
try dbQueue.read { db in
print("> KISS: Fetch from query interface request")
let request = Base.filter(Column("type") == "Foo") // Define a request
let rows = try Row.fetchAll(db, request) // Fetch database rows
let bases = rows.map { row in // Decode database rows
Base.decode(row: row)
}
for base in bases { // Use fetched values
print(base.description)
}
}
//: As seen above, we can perform polymorphic requests with the standard GRDB,
//: by fetching raw rows and mapping them through a decoding method.
//:
//: The resulting code is not as streamlined as usual GRDB code, but we could
//: already do what we needed without much effort.
//:
//: ### Custom Protocol: MyDatabaseDecoder
//:
//: In the rest of this playground, we will define a **new realm of requests**.
//:
//: GRDB ships with three built-in realms of requests: requests of raw rows,
//: requests of values, and requests of record types that adopt the
//: `FetchableRecord` protocol.
//:
//: We'll define requests of record types that adopt the custom
//: `MyDatabaseDecoder` protocol:
protocol MyDatabaseDecoder {
associatedtype DecodedType
static func decode(row: Row) -> DecodedType
}
//: Types that adopt the MyDatabaseDecoder protocol are able, among other
//: things, to perform polymorphic decoding. Our Base class, for example:
extension Base: MyDatabaseDecoder {
// Already declared above:
// static func decode(row: Row) -> Base { ... }
}
//: Now let's see how we can define a new realm of requests based on the
//: `MyDatabaseDecoder` protocol. Our goal is to make them just as powerful as
//: ready-made requests of rows, values and FetchableRecord.
//:
//: All we need is a set of *extensions* that define the classic GRDB fetching
//: methods: `fetchOne`, `fetchAll`, and `fetchCursor`. The most fundamental one
//: is `fetchCursor`, because from it we can derive the two others.
//:
//: The first extension is the most low-level one: fetching from SQLite
//: **prepared statement**:
//:
//: try dbQueue.read { db in
//: let statement = try db.makeStatement(sql: "SELECT ...")
//: try Base.fetchCursor(statement) // Cursor of Base
//: try Base.fetchAll(statement) // [Base]
//: try Base.fetchOne(statement) // Base?
//: }
extension MyDatabaseDecoder {
// MARK: - Fetch from Prepared Statement
// Statement, StatementArguments, and RowAdapter are the fundamental
// fetching parameters of GRDB. Make sure to accept them all:
static func fetchCursor(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
// Turn the cursor of raw rows into a cursor of decoded rows
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
self.decode(row: $0)
}
}
static func fetchAll(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [DecodedType] {
// Turn the cursor into an Array
return try Array(fetchCursor(statement, arguments: arguments, adapter: adapter))
}
static func fetchOne(_ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> DecodedType? {
// Consume the first value of the cursor
return try fetchCursor(statement, arguments: arguments, adapter: adapter).next()
}
}
try dbQueue.read { db in
print("> Fetch from prepared statement")
let statement = try db.makeStatement(sql: "SELECT * FROM base")
let bases = try Base.fetchAll(statement)
for base in bases {
print(base.description)
}
}
//: Now that we can fetch from prepared statements, we can fetch when given a
//: **request**, as defined by the `FetchRequest` protocol. This is the
//: protocol for query interface requests such as `Base.all()`, or
//: `SQLRequest`, etc.
//:
//: try dbQueue.read { db in
//: let request = Base.all()
//: try Base.fetchCursor(db, request) // Cursor of Base
//: try Base.fetchAll(db, request) // [Base]
//: try Base.fetchOne(db, request) // Base?
//: }
extension MyDatabaseDecoder {
// MARK: - Fetch from FetchRequest
static func fetchCursor<R: FetchRequest>(_ db: Database, _ request: R) throws -> MapCursor<RowCursor, DecodedType> {
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchCursor(preparedRequest.statement, adapter: preparedRequest.adapter)
}
static func fetchAll<R: FetchRequest>(_ db: Database, _ request: R) throws -> [DecodedType] {
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: false)
return try fetchAll(preparedRequest.statement, adapter: preparedRequest.adapter)
}
static func fetchOne<R: FetchRequest>(_ db: Database, _ request: R) throws -> DecodedType? {
// The `forSingleResult: true` argument hints the request that a single
// row will be consumed. Some requests will add a LIMIT SQL clause.
let preparedRequest = try request.makePreparedRequest(db, forSingleResult: true)
return try fetchOne(preparedRequest.statement, adapter: preparedRequest.adapter)
}
}
try dbQueue.read { db in
print("> Fetch given a request")
let request = Base.all()
let bases = try Base.fetchAll(db, request)
for base in bases {
print(base.description)
}
}
//: When it's fine to fetch given a request, it's even better when requests can
//: fetch, too:
//:
//: try dbQueue.read { db in
//: let request = Base.all()
//: try request.fetchCursor(db) // Cursor of Base
//: try request.fetchAll(db) // [Base]
//: try request.fetchOne(db) // Base?
//: }
extension FetchRequest where RowDecoder: MyDatabaseDecoder {
// MARK: - FetchRequest fetching methods
func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, RowDecoder.DecodedType> {
try RowDecoder.fetchCursor(db, self)
}
func fetchAll(_ db: Database) throws -> [RowDecoder.DecodedType] {
try RowDecoder.fetchAll(db, self)
}
func fetchOne(_ db: Database) throws -> RowDecoder.DecodedType? {
try RowDecoder.fetchOne(db, self)
}
}
try dbQueue.read { db in
print("> Fetch from request")
let request = Base.all()
let bases = try request.fetchAll(db)
for base in bases {
print(base.description)
}
}
//: Types that adopt both FetchableRecord and TableRecord are able to fetch
//: right from the base type. Let's allow this as well for MyDatabaseDecoder:
//:
//: try dbQueue.read { db in
//: try Base.fetchCursor(db) // Cursor of Base
//: try Base.fetchAll(db) // [Base]
//: try Base.fetchOne(db) // Base?
//: }
extension MyDatabaseDecoder where Self: TableRecord {
// MARK: - Static fetching methods
static func fetchCursor(_ db: Database) throws -> MapCursor<RowCursor, DecodedType> {
try all().fetchCursor(db)
}
static func fetchAll(_ db: Database) throws -> [DecodedType] {
try all().fetchAll(db)
}
static func fetchOne(_ db: Database) throws -> DecodedType? {
try all().fetchOne(db)
}
}
try dbQueue.read { db in
print("> Fetch from base type")
let bases = try Base.fetchAll(db)
for base in bases {
print(base.description)
}
}
//: Finally, you can support raw SQL as well:
//:
//: try dbQueue.read { db in
//: try Base.fetchAll(db,
//: sql: "SELECT ... WHERE name = ?",
//: arguments: ["O'Brien"]) // [Base]
//: }
extension MyDatabaseDecoder {
// MARK: - Fetch from SQL
static func fetchCursor(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> MapCursor<RowCursor, DecodedType> {
try fetchCursor(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
static func fetchAll(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [DecodedType] {
try fetchAll(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
static func fetchOne(_ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> DecodedType? {
try fetchOne(db, SQLRequest(sql: sql, arguments: arguments, adapter: adapter))
}
}
try dbQueue.read { db in
print("> Fetch from SQL")
let bases = try Base.fetchAll(db, sql: "SELECT * FROM base")
for base in bases {
print(base.description)
}
}
//: Voilà! Our `MyDatabaseDecoder` protocol is now as able as the built-in
//: `FetchableRecord` protocol.
//:
//: To sum up, you have learned:
//:
//: - how to keep things simple: as long as you can fetch rows, you can decode
//: them the way you want.
//: - how to define a whole new realm of requests based on a custom protocol.
//: This involves writing a few extensions that give your protocol the same
//: fluent interface that is ready-made for the built-in FetchableRecord
//: protocol. This is more work, but you are granted with the full
//: customization freedom.
//:
//: To end this tour, let's quickly look at two other possible customized
//: row decoding strategies.
//:
//: ## An Example: Contextualized Records
//:
//: Your application needs to decode rows with a context: each decoded value
//: should be initialized with some extra value that does not come from
//: the database.
//:
//: In this case, you may define a `ContextFetchableRecord` protocol, and
//: derive all other fetching methods from the most fundamental one, which
//: fetches a cursor from a prepared statement (as we did for the
//: MyDatabaseDecoder protocol, above):
protocol ContextFetchableRecord {
associatedtype Context
init(row: Row, context: Context)
}
extension ContextFetchableRecord {
static func fetchCursor(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil,
context: Context)
throws -> MapCursor<RowCursor, Self>
{
// Turn the cursor of raw rows into a cursor of decoded rows
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
self.init(row: $0, context: context)
}
}
// Define fetchAll, fetchOne, and other extensions...
}
//: ## An Example: Failable Records
//:
//: Your application needs a record type that supports untrusted databases,
//: and may fail at decoding database rows (throw an error when a row contains
//: invalid values).
//:
//: In this case, you may define a `FailableFetchableRecord` protocol, and
//: derive all other fetching methods from the most fundamental one, which
//: fetches a cursor from a prepared statement (as we did for the
//: MyDatabaseDecoder protocol, above):
protocol FailableFetchableRecord {
init(row: Row) throws
}
extension FailableFetchableRecord {
static func fetchCursor(
_ statement: Statement,
arguments: StatementArguments? = nil,
adapter: RowAdapter? = nil)
throws -> MapCursor<RowCursor, Self>
{
// Turn the cursor of raw rows into a cursor of decoded rows
return try Row.fetchCursor(statement, arguments: arguments, adapter: adapter).map {
try self.init(row: $0)
}
}
// Define fetchAll, fetchOne, and other extensions...
}
@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<playground version='5.0' target-platform='macos' display-mode='rendered' buildActiveScheme='true'>
<timeline fileName='timeline.xctimeline'/>
</playground>
-3
View File
@@ -10,9 +10,6 @@
<FileRef
location = "group:TransactionObserver.playground">
</FileRef>
<FileRef
location = "group:CustomizedDecodingOfDatabaseRows.playground">
</FileRef>
<FileRef
location = "group:Associations.playground">
</FileRef>
+16 -16
View File
@@ -487,7 +487,7 @@ extension Row {
/// let request = Book.including(required: Book.author)
/// let row = try Row.fetchOne(db, request)!
///
/// print(Book(row: row).title)
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let author: Author = row["author"]
@@ -499,7 +499,7 @@ extension Row {
/// let request = Book.including(required: Book.author.including(required: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// print(Book(row: row).title)
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let country: Country = row["country"]
@@ -522,7 +522,7 @@ extension Row {
/// let request = Book.including(optional: Book.author)
/// let row = try Row.fetchOne(db, request)!
///
/// print(Book(row: row).title)
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let author: Author? = row["author"]
@@ -534,7 +534,7 @@ extension Row {
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// print(Book(row: row).title)
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let country: Country? = row["country"]
@@ -557,7 +557,7 @@ extension Row {
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// print(Author(row: row).name)
/// try print(Author(row: row).name)
/// // Prints "Herman Melville"
///
/// let books: [Book] = row["books"]
@@ -579,7 +579,7 @@ extension Row {
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// print(Author(row: row).name)
/// try print(Author(row: row).name)
/// // Prints "Herman Melville"
///
/// let books: Set<Book> = row["books"]
@@ -872,7 +872,7 @@ extension Row {
/// let request = Book.including(optional: Book.author)
/// let row = try Row.fetchOne(db, request)!
///
/// print(Book(row: row).title)
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let author: Author? = row["author"]
@@ -884,7 +884,7 @@ extension Row {
/// let request = Book.including(optional: Book.author.including(optional: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// print(Book(row: row).title)
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let country: Country? = row["country"]
@@ -904,7 +904,7 @@ extension Row {
guard let scopedRow = scopesTree[scope], scopedRow.containsNonNullValue else {
return nil
}
return Record(row: scopedRow)
return try Record(row: scopedRow)
}
/// Returns the record associated with the given scope.
@@ -914,7 +914,7 @@ extension Row {
/// let request = Book.including(required: Book.author)
/// let row = try Row.fetchOne(db, request)!
///
/// print(Book(row: row).title)
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let author: Author = row["author"]
@@ -926,7 +926,7 @@ extension Row {
/// let request = Book.including(required: Book.author.including(required: Author.country))
/// let row = try Row.fetchOne(db, request)!
///
/// print(Book(row: row).title)
/// try print(Book(row: row).title)
/// // Prints "Moby-Dick"
///
/// let country: Country = row["country"]
@@ -973,7 +973,7 @@ extension Row {
scope \(String(reflecting: scope)) only contains null values
"""))
}
return Record(row: scopedRow)
return try Record(row: scopedRow)
}
}
@@ -987,7 +987,7 @@ extension Row {
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// print(Author(row: row).name)
/// try print(Author(row: row).name)
/// // Prints "Herman Melville"
///
/// let books: [Book] = row["books"]
@@ -1026,7 +1026,7 @@ extension Row {
var collection = Collection()
collection.reserveCapacity(rows.count)
for row in rows {
collection.append(Collection.Element(row: row))
try collection.append(Collection.Element(row: row))
}
return collection
}
@@ -1038,7 +1038,7 @@ extension Row {
/// let request = Author.including(all: Author.books)
/// let row = try Row.fetchOne(db, request)!
///
/// print(Author(row: row).name)
/// try print(Author(row: row).name)
/// // Prints "Herman Melville"
///
/// let books: Set<Book> = row["books"]
@@ -1072,7 +1072,7 @@ extension Row {
}
var set = Set<Record>(minimumCapacity: rows.count)
for row in rows {
set.insert(Record(row: row))
try set.insert(Record(row: row))
}
return set
}
@@ -458,7 +458,7 @@ struct SQLQueryGenerator: Refinable {
/// let request = Book.all()
/// for row in try Row.fetchAll(db, request) {
/// row // [id:1, title:"Moby-Dick"]
/// let book = Book(row: row)
/// let book = try Book(row: row)
/// }
///
/// But as soon as the selection includes columns of a included relation,
@@ -468,7 +468,7 @@ struct SQLQueryGenerator: Refinable {
/// let request = Book.including(required: Book.author)
/// for row in try Row.fetchAll(db, request) {
/// row // [id:1, title:"Moby-Dick"]
/// let book = Book(row: row)
/// let book = try Book(row: row)
///
/// row.scopes["author"] // [id:12, name:"Herman Melville"]
/// let author: Author = row["author"]
@@ -644,7 +644,7 @@ private struct SQLQualifiedRelation {
// The RangeRowAdapter hides the columns appended by joined relations:
//
// row // [id:1, title:"Moby-Dick"]
// let book = Book(row: row)
// let book = try Book(row: row)
//
// Scopes give access to those joined relations:
//
+3 -5
View File
@@ -1,10 +1,8 @@
import Foundation
extension FetchableRecord where Self: Decodable {
public init(row: Row) {
// Intended force-try. FetchableRecord is designed for records that
// reliably decode from rows.
self = try! RowDecoder().decode(from: row)
public init(row: Row) throws {
self = try RowDecoder().decode(from: row)
}
}
@@ -342,7 +340,7 @@ private struct _RowDecoder<R: FetchableRecord>: Decoder {
{
if let type = T.self as? any FetchableRecord.Type {
// Prefer FetchableRecord decoding over Decodable.
return type.init(row: row) as! T
return try type.init(row: row) as! T
} else {
let decoder = _RowDecoder(row: row, codingPath: codingPath, columnDecodingStrategy: .useDefaultKeys)
return try T(from: decoder)
+6 -6
View File
@@ -25,7 +25,7 @@ public protocol FetchableRecord {
/// For performance reasons, the row argument may be reused during the
/// iteration of a fetch query. If you want to keep the row for later use,
/// make sure to store a copy: `self.row = row.copy()`.
init(row: Row)
init(row: Row) throws
// MARK: - Customizing the Format of Database Columns
@@ -384,7 +384,7 @@ extension FetchableRecord {
if let supplementaryFetch = request.supplementaryFetch {
let rows = try Row.fetchAll(request.statement, adapter: request.adapter)
try supplementaryFetch(db, rows)
return rows.map(Self.init(row:))
return try rows.map(Self.init(row:))
} else {
return try fetchAll(request.statement, adapter: request.adapter)
}
@@ -407,7 +407,7 @@ extension FetchableRecord {
return nil
}
try supplementaryFetch(db, [row])
return .init(row: row)
return try .init(row: row)
} else {
return try fetchOne(request.statement, adapter: request.adapter)
}
@@ -430,7 +430,7 @@ extension FetchableRecord where Self: Hashable {
if let supplementaryFetch = request.supplementaryFetch {
let rows = try Row.fetchAll(request.statement, adapter: request.adapter)
try supplementaryFetch(db, rows)
return Set(rows.lazy.map(Self.init(row:)))
return try Set(rows.lazy.map(Self.init(row:)))
} else {
return try fetchSet(request.statement, adapter: request.adapter)
}
@@ -535,8 +535,8 @@ public final class RecordCursor<Record: FetchableRecord>: DatabaseCursor {
}
/// :nodoc:
public func _element(sqliteStatement: SQLiteStatement) -> Record {
Record(row: row)
public func _element(sqliteStatement: SQLiteStatement) throws -> Record {
try Record(row: row)
}
}
+1 -1
View File
@@ -11,7 +11,7 @@ open class Record: FetchableRecord, TableRecord, PersistableRecord {
}
/// Creates a Record from a row.
public required init(row: Row) {
public required init(row: Row) throws {
if row.isFetched {
// Take care of the hasDatabaseChanges flag.
//
+7 -11
View File
@@ -2663,7 +2663,7 @@ Details follow:
```swift
protocol FetchableRecord {
/// Row initializer
init(row: Row)
init(row: Row) throws
}
```
@@ -3334,14 +3334,14 @@ class Place: Record {
}
/// Creates a record from a database row
required init(row: Row) {
required init(row: Row) throws {
id = row[Columns.id]
title = row[Columns.title]
isFavorite = row[Columns.favorite]
coordinate = CLLocationCoordinate2D(
latitude: row[Columns.latitude],
longitude: row[Columns.longitude])
super.init(row: row)
try super.init(row: row)
}
/// The values persisted in the database
@@ -3717,12 +3717,8 @@ When SQLite won't let you provide an explicit primary key (as in [full-text](Doc
- Your application needs to decode rows with a context: each decoded value should be initialized with some extra value that does not come from the database.
- Your application needs a record type that supports untrusted databases, and may fail at decoding database rows (throw an error when a row contains invalid values).
Since those use cases are not well handled by FetchableRecord, don't try to implement them on top of this protocol: you'll just fight the framework.
Instead, please have a look at the [CustomizedDecodingOfDatabaseRows](Documentation/Playgrounds/CustomizedDecodingOfDatabaseRows.playground/Contents.swift) playground. You'll run some sample code, and learn how to escape FetchableRecord when you need. And remember that leaving FetchableRecord will not deprive you of [query interface requests](#requests) and generally all SQL generation features of the [TableRecord] and [PersistableRecord] protocols.
## Examples of Record Definitions
@@ -3953,14 +3949,14 @@ class Place: Record {
}
/// Creates a record from a database row
required init(row: Row) {
required init(row: Row) throws {
id = row[Columns.id]
title = row[Columns.title]
isFavorite = row[Columns.isFavorite]
coordinate = CLLocationCoordinate2D(
latitude: row[Columns.latitude],
longitude: row[Columns.longitude])
super.init(row: row)
try super.init(row: row)
}
/// The values persisted in the database
@@ -6284,7 +6280,7 @@ let request = Player.filter(id: 42)
let observation = ValueObservation
.tracking { db in try Row.fetchOne(db, request) }
.removeDuplicates() // Row adopts Equatable
.map { row in row.map(Player.init(row:) }
.map { row in try row.map(Player.init(row:) }
```
This technique is also available for requests that involve [Associations]:
@@ -6300,7 +6296,7 @@ let request = Team.including(all: Team.players)
let observation = ValueObservation
.tracking { db in try Row.fetchAll(db, request) }
.removeDuplicates() // Row adopts Equatable
.map { rows in rows.map(TeamInfo.init(row:) }
.map { rows in try rows.map(TeamInfo.init(row:) }
```
@@ -20,8 +20,8 @@ private struct PlayerWithRequiredTeam: FetchableRecord {
var player: Player
var team: Team
init(row: Row) {
player = Player(row: row)
init(row: Row) throws {
player = try Player(row: row)
team = row[Player.teamScope]
}
}
@@ -30,8 +30,8 @@ private struct PlayerWithOptionalTeam: FetchableRecord {
var player: Player
var team: Team?
init(row: Row) {
player = Player(row: row)
init(row: Row) throws {
player = try Player(row: row)
team = row[Player.teamScope]
}
}
@@ -40,8 +40,8 @@ private struct PlayerWithTeamName: FetchableRecord {
var player: Player
var teamName: String?
init(row: Row) {
player = Player(row: row)
init(row: Row) throws {
player = try Player(row: row)
teamName = row["teamName"]
}
}
@@ -25,8 +25,8 @@ private struct AWithRequiredC: FetchableRecord {
var a: A
var c: C
init(row: Row) {
a = A(row: row)
init(row: Row) throws {
a = try A(row: row)
c = row["c"]
}
}
@@ -35,8 +35,8 @@ private struct AWithOptionalC: FetchableRecord {
var a: A
var c: C?
init(row: Row) {
a = A(row: row)
init(row: Row) throws {
a = try A(row: row)
c = row["c"]
}
}
@@ -46,8 +46,8 @@ private struct AWithRequiredBAndOptionalC: FetchableRecord {
var b: B
var c: C?
init(row: Row) {
a = A(row: row)
init(row: Row) throws {
a = try A(row: row)
b = row["b"]
c = row["c"]
}
@@ -57,8 +57,8 @@ private struct AWithCName: FetchableRecord {
var a: A
var cName: String?
init(row: Row) {
a = A(row: row)
init(row: Row) throws {
a = try A(row: row)
cName = row["cName"]
}
}
@@ -68,8 +68,8 @@ private struct AWithRequiredBNameAndOptionalCName: FetchableRecord {
var bName: String
var cName: String?
init(row: Row) {
a = A(row: row)
init(row: Row) throws {
a = try A(row: row)
bName = row["bName"]
cName = row["cName"]
}
@@ -93,7 +93,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: nil),
@@ -109,7 +109,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: nil))
}
@@ -141,7 +141,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: nil),
@@ -157,7 +157,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: nil))
}
@@ -185,7 +185,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [
@@ -206,7 +206,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [
B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
@@ -225,7 +225,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [
@@ -246,7 +246,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [
B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
@@ -265,7 +265,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [
@@ -286,7 +286,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [
B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
@@ -321,7 +321,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [
@@ -342,7 +342,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [
B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
@@ -377,7 +377,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs1: [
@@ -398,7 +398,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs1: [
B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
@@ -434,7 +434,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [1]),
@@ -450,7 +450,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [1]))
}
@@ -466,7 +466,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [1]),
@@ -482,7 +482,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
bs: [1]))
}
@@ -517,7 +517,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
cs: [
@@ -551,7 +551,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
cs: [
Record.CInfo(
@@ -587,7 +587,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
cs: []),
@@ -603,7 +603,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
cs: []))
}
@@ -659,7 +659,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
cs1: [],
@@ -705,7 +705,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
cs1: [],
cs2: [
@@ -747,7 +747,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
cs: [
@@ -777,7 +777,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
cs: [
Record.CInfo(
@@ -811,7 +811,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
cs: []),
@@ -827,7 +827,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
cs: []))
}
@@ -883,7 +883,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
cs1: [],
@@ -917,7 +917,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
cs1: [],
cs2: [
@@ -950,7 +950,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
ds: [
@@ -972,7 +972,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
ds: [
D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]),
@@ -1010,7 +1010,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
ds1: [],
@@ -1037,7 +1037,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
a: A(row: ["cola1": 1, "cola2": "a1"]),
ds1: [],
ds2: [
@@ -1077,7 +1077,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
a: Record.AInfo(
@@ -1109,7 +1109,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
a: Record.AInfo(
a: A(row: ["cola1": 1, "cola2": "a1"]),
@@ -1130,7 +1130,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
a: A(row: ["cola1": 1, "cola2": "a1"]),
@@ -1160,7 +1160,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
a: A(row: ["cola1": 1, "cola2": "a1"]),
cs: [
@@ -1217,7 +1217,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
a1: Record.AInfo(
@@ -1257,7 +1257,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
b: B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
a1: Record.AInfo(
a: A(row: ["cola1": 1, "cola2": "a1"]),
@@ -1294,7 +1294,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchAll
do {
let records = try Record.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
Record(
d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]),
bs: [
@@ -1325,7 +1325,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
// Record.fetchOne
do {
let record = try Record.fetchOne(db, request)!
XCTAssertEqual(record, Record(
try XCTAssertEqual(record, Record(
d: D(row: ["cold1": 10, "cold2": 7, "cold3": "d1"]),
bs: [
B(row: ["colb1": 4, "colb2": 1, "colb3": "b1"]),
@@ -1447,7 +1447,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
.orderByPrimaryKey()
let records = try XRecord.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
XRecord(
xa: XA(row: ["cola1": 1, "cola2": "a1"]),
xbs: [
@@ -1478,7 +1478,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
.orderByPrimaryKey()
let records = try XRecord.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
XRecord(
xa: XA(row: ["cola1": 1, "cola2": "a1"]),
bs: [
@@ -1509,7 +1509,7 @@ class AssociationPrefetchingCodableRecordTests: GRDBTestCase {
.orderByPrimaryKey()
let records = try XRecord.fetchAll(db, request)
XCTAssertEqual(records, [
try XCTAssertEqual(records, [
XRecord(
a: A(row: ["cola1": 1, "cola2": "a1"]),
xbs: [
@@ -97,8 +97,8 @@ class AssociationRowScopeSearchTests: GRDBTestCase {
var b: B
var c: C
var d: D
init(row: Row) {
a = A(row: row)
init(row: Row) throws {
a = try A(row: row)
b = row["b"]
c = row["c"]
d = row["d"]
+2 -2
View File
@@ -172,7 +172,7 @@ class ColumnExpressionTests: GRDBTestCase {
try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.Columns.id)).databaseRegion(db).description, "player(full_name,id,score)[1,2,3]")
// Test specific column updates
let player = Player(row: ["id": 1, "full_name": "Arthur", "score": 1000])
let player = try Player(row: ["id": 1, "full_name": "Arthur", "score": 1000])
try? player.update(db, columns: [Player.Columns.name, Player.Columns.score])
XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"full_name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1")
@@ -220,7 +220,7 @@ class ColumnExpressionTests: GRDBTestCase {
try XCTAssertEqual(Player.filter([1, 2, 3].contains(Player.CodingKeys.id)).databaseRegion(db).description, "player(full_name,id,score)[1,2,3]")
// Test specific column updates
let player = Player(row: ["id": 1, "full_name": "Arthur", "score": 1000])
let player = try Player(row: ["id": 1, "full_name": "Arthur", "score": 1000])
try? player.update(db, columns: [Player.CodingKeys.name, Player.CodingKeys.score])
XCTAssertEqual(lastSQLQuery, "UPDATE \"player\" SET \"full_name\"=\'Arthur\', \"score\"=1000 WHERE \"id\"=1")
@@ -111,6 +111,10 @@ private class UserFetchableRecord2 : FetchableRecord {
required init(row: Row) { }
}
private struct UserFetchableRecord3 : FetchableRecord {
init(row: Row) throws { }
}
// MARK: - StatementColumnConvertible
private struct UserStatementColumnConvertible1 : StatementColumnConvertible {
@@ -7,7 +7,7 @@ import GRDB
private class UserRecord : Record {
override init() { super.init() }
required init(row: Row) { super.init(row: row) }
required init(row: Row) throws { try super.init(row: row) }
override class var databaseTableName: String { super.databaseTableName }
override class var persistenceConflictPolicy: PersistenceConflictPolicy { super.persistenceConflictPolicy }
override class var databaseSelection: [any SQLSelectable] { super.databaseSelection }
@@ -8,18 +8,18 @@ class FetchableRecordDecodableTests: GRDBTestCase { }
extension FetchableRecordDecodableTests {
func testTrivialDecodable() {
func testTrivialDecodable() throws {
struct Struct : FetchableRecord, Decodable {
let value: String
}
do {
let s = Struct(row: ["value": "foo"])
let s = try Struct(row: ["value": "foo"])
XCTAssertEqual(s.value, "foo")
}
}
func testCustomDecodable() {
func testCustomDecodable() throws {
struct Struct : FetchableRecord, Decodable {
let value: String
@@ -34,7 +34,7 @@ extension FetchableRecordDecodableTests {
}
do {
let s = Struct(row: ["someColumn": "foo"])
let s = try Struct(row: ["someColumn": "foo"])
XCTAssertEqual(s.value, "foo")
}
}
@@ -59,7 +59,7 @@ extension FetchableRecordDecodableTests {
extension FetchableRecordDecodableTests {
func testTrivialProperty() {
func testTrivialProperty() throws {
struct Struct : FetchableRecord, Decodable {
let int64: Int64
let optionalInt64: Int64?
@@ -67,25 +67,25 @@ extension FetchableRecordDecodableTests {
do {
// No null values
let s = Struct(row: ["int64": 1, "optionalInt64": 2])
let s = try Struct(row: ["int64": 1, "optionalInt64": 2])
XCTAssertEqual(s.int64, 1)
XCTAssertEqual(s.optionalInt64, 2)
}
do {
// Null values
let s = Struct(row: ["int64": 2, "optionalInt64": nil])
let s = try Struct(row: ["int64": 2, "optionalInt64": nil])
XCTAssertEqual(s.int64, 2)
XCTAssertNil(s.optionalInt64)
}
do {
// Missing and extra values
let s = Struct(row: ["int64": 3, "ignored": "?"])
let s = try Struct(row: ["int64": 3, "ignored": "?"])
XCTAssertEqual(s.int64, 3)
XCTAssertNil(s.optionalInt64)
}
}
func testTrivialSingleValueDecodableProperty() {
func testTrivialSingleValueDecodableProperty() throws {
struct Value : Decodable {
let string: String
@@ -101,27 +101,27 @@ extension FetchableRecordDecodableTests {
do {
// No null values
let s = Struct(row: ["value": "foo", "optionalValue": "bar"])
let s = try Struct(row: ["value": "foo", "optionalValue": "bar"])
XCTAssertEqual(s.value.string, "foo")
XCTAssertEqual(s.optionalValue!.string, "bar")
}
do {
// Null values
let s = Struct(row: ["value": "foo", "optionalValue": nil])
let s = try Struct(row: ["value": "foo", "optionalValue": nil])
XCTAssertEqual(s.value.string, "foo")
XCTAssertNil(s.optionalValue)
}
do {
// Missing and extra values
let s = Struct(row: ["value": "foo", "ignored": "?"])
let s = try Struct(row: ["value": "foo", "ignored": "?"])
XCTAssertEqual(s.value.string, "foo")
XCTAssertNil(s.optionalValue)
}
}
func testNonTrivialSingleValueDecodableProperty() {
func testNonTrivialSingleValueDecodableProperty() throws {
struct NestedValue : Decodable {
let string: String
@@ -145,27 +145,27 @@ extension FetchableRecordDecodableTests {
do {
// No null values
let s = Struct(row: ["value": "foo", "optionalValue": "bar"])
let s = try Struct(row: ["value": "foo", "optionalValue": "bar"])
XCTAssertEqual(s.value.nestedValue.string, "foo")
XCTAssertEqual(s.optionalValue!.nestedValue.string, "bar")
}
do {
// Null values
let s = Struct(row: ["value": "foo", "optionalValue": nil])
let s = try Struct(row: ["value": "foo", "optionalValue": nil])
XCTAssertEqual(s.value.nestedValue.string, "foo")
XCTAssertNil(s.optionalValue)
}
do {
// Missing and extra values
let s = Struct(row: ["value": "foo", "ignored": "?"])
let s = try Struct(row: ["value": "foo", "ignored": "?"])
XCTAssertEqual(s.value.nestedValue.string, "foo")
XCTAssertNil(s.optionalValue)
}
}
func testDecodableRawRepresentableProperty() {
func testDecodableRawRepresentableProperty() throws {
// This test is somewhat redundant with testSingleValueDecodableProperty,
// since a RawRepresentable enum is a "single-value" Decodable.
//
@@ -182,27 +182,27 @@ extension FetchableRecordDecodableTests {
do {
// No null values
let s = Struct(row: ["value": "foo", "optionalValue": "bar"])
let s = try Struct(row: ["value": "foo", "optionalValue": "bar"])
XCTAssertEqual(s.value, .foo)
XCTAssertEqual(s.optionalValue!, .bar)
}
do {
// Null values
let s = Struct(row: ["value": "foo", "optionalValue": nil])
let s = try Struct(row: ["value": "foo", "optionalValue": nil])
XCTAssertEqual(s.value, .foo)
XCTAssertNil(s.optionalValue)
}
do {
// Missing and extra values
let s = Struct(row: ["value": "foo", "ignored": "?"])
let s = try Struct(row: ["value": "foo", "ignored": "?"])
XCTAssertEqual(s.value, .foo)
XCTAssertNil(s.optionalValue)
}
}
func testDatabaseValueConvertibleProperty() {
func testDatabaseValueConvertibleProperty() throws {
// This test makes sure that Date, for example, can be read from a String.
//
// Without this preference for fromDatabaseValue(_:) over init(from:Decoder),
@@ -238,21 +238,21 @@ extension FetchableRecordDecodableTests {
do {
// No null values
let s = Struct(row: ["value": "foo", "optionalValue": "bar"])
let s = try Struct(row: ["value": "foo", "optionalValue": "bar"])
XCTAssertEqual(s.value.string, "foo (DatabaseValueConvertible)")
XCTAssertEqual(s.optionalValue!.string, "bar (DatabaseValueConvertible)")
}
do {
// Null values
let s = Struct(row: ["value": "foo", "optionalValue": nil])
let s = try Struct(row: ["value": "foo", "optionalValue": nil])
XCTAssertEqual(s.value.string, "foo (DatabaseValueConvertible)")
XCTAssertNil(s.optionalValue)
}
do {
// Missing and extra values
let s = Struct(row: ["value": "foo", "ignored": "?"])
let s = try Struct(row: ["value": "foo", "ignored": "?"])
XCTAssertEqual(s.value.string, "foo (DatabaseValueConvertible)")
XCTAssertNil(s.optionalValue)
}
@@ -263,33 +263,33 @@ extension FetchableRecordDecodableTests {
extension FetchableRecordDecodableTests {
func testStructWithDate() {
func testStructWithDate() throws {
struct StructWithDate : FetchableRecord, Decodable {
let date: Date
}
let date = Date()
let value = StructWithDate(row: ["date": date])
let value = try StructWithDate(row: ["date": date])
XCTAssert(abs(value.date.timeIntervalSince(date)) < 0.001)
}
func testStructWithURL() {
func testStructWithURL() throws {
struct StructWithURL : FetchableRecord, Decodable {
let url: URL
}
let url = URL(string: "https://github.com")
let value = StructWithURL(row: ["url": url])
let value = try StructWithURL(row: ["url": url])
XCTAssertEqual(value.url, url)
}
func testStructWithUUID() {
func testStructWithUUID() throws {
struct StructWithUUID : FetchableRecord, Decodable {
let uuid: UUID
}
let uuid = UUID()
let value = StructWithUUID(row: ["uuid": uuid])
let value = try StructWithUUID(row: ["uuid": uuid])
XCTAssertEqual(value.uuid, uuid)
}
}
@@ -585,7 +585,7 @@ extension FetchableRecordDecodableTests {
{"firstName":"Bob","lastName":"Dylan"}
"""]
let model = StructWithNestedType(row: row)
let model = try StructWithNestedType(row: row)
XCTAssertEqual(model.nested.firstName, "Bob")
XCTAssertEqual(model.nested.lastName, "Dylan")
}
@@ -1247,7 +1247,7 @@ extension FetchableRecordDecodableTests {
test(record)
let row = try Row.fetchOne(db, request)!
test(Record(row: row))
try test(Record(row: row))
}
}
@@ -1282,7 +1282,7 @@ extension FetchableRecordDecodableTests {
test(record)
let row = try Row.fetchOne(db, request)!
test(Record(row: row))
try test(Record(row: row))
}
}
@@ -1319,7 +1319,7 @@ extension FetchableRecordDecodableTests {
test(record)
let row = try Row.fetchOne(db, request)!
test(CustomizedRecord(row: row))
try test(CustomizedRecord(row: row))
}
}
@@ -1354,7 +1354,7 @@ extension FetchableRecordDecodableTests {
test(record)
let row = try Row.fetchOne(db, request)!
test(CustomizedRecord(row: row))
try test(CustomizedRecord(row: row))
}
}
@@ -289,11 +289,11 @@ class MutablePersistableRecordChangesTests: GRDBTestCase {
case id, firstName, lastName
}
required init(row: Row) {
required init(row: Row) throws {
id = row[Columns.id]
firstName = row[Columns.firstName]
lastName = row[Columns.lastName]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -13,11 +13,11 @@ private class Reader : Record {
super.init()
}
required init(row: Row){
required init(row: Row) throws {
self.id = row["id"]
self.name = row["name"]
self.age = row["age"]
super.init(row: row)
try super.init(row: row)
}
override class var databaseTableName: String {
+10 -10
View File
@@ -31,12 +31,12 @@ private class Person : Record {
"persons"
}
required init(row: Row) {
required init(row: Row) throws {
id = row["id"]
age = row["age"]
name = row["name"]
creationDate = row["creationDate"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -70,9 +70,9 @@ private class IntegerPropertyOnRealAffinityColumn : Record {
// Record
required init(row: Row) {
required init(row: Row) throws {
value = row["value"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -100,12 +100,12 @@ private class PersonWithModifiedCaseColumns: Record {
"persons"
}
required init(row: Row) {
required init(row: Row) throws {
id = row["ID"]
age = row["AGE"]
name = row["NAME"]
creationDate = row["CREATIONDATE"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -144,11 +144,11 @@ class RecordEditedTests: GRDBTestCase {
XCTAssertTrue(person.hasDatabaseChanges)
}
func testRecordIsEditedAfterInitFromRow() {
func testRecordIsEditedAfterInitFromRow() throws {
// Create a Record from a row. The row may not come from the database.
// So it is edited.
let row = Row(["name": "Arthur", "age": 41])
let person = Person(row: row)
let person = try Person(row: row)
XCTAssertTrue(person.hasDatabaseChanges)
}
@@ -398,8 +398,8 @@ class RecordEditedTests: GRDBTestCase {
}
}
func testChangesAfterInitFromRow() {
let person = Person(row: Row(["name": "Arthur", "age": 41]))
func testChangesAfterInitFromRow() throws {
let person = try Person(row: Row(["name": "Arthur", "age": 41]))
let changes = person.databaseChanges
XCTAssertEqual(changes.count, 4)
for (column, old) in changes {
+15 -15
View File
@@ -19,8 +19,8 @@ class EmptyRecordWithoutInitializer : Record {
class RecordWithMutablePropertyAndRowInitializer : Record {
var name: String?
required init(row: Row) {
super.init(row: row) // super.init(row: row) is required
required init(row: Row) throws {
try super.init(row: row) // super.init(row: row) is required
self.name = "toto" // property can be set before or after super.init
}
}
@@ -34,8 +34,8 @@ class RecordWithMutablePropertyAndEmptyInitializer : Record {
self.name = "toto" // property can be set before or after super.init
}
required init(row: Row) { // init(row) is required
super.init(row: row) // super.init(row: row) is required
required init(row: Row) throws { // init(row) is required
try super.init(row: row) // super.init(row: row) is required
}
}
@@ -48,8 +48,8 @@ class RecordWithMutablePropertyAndCustomInitializer : Record {
super.init() // super.init() is required
}
required init(row: Row) { // init(row) is required
super.init(row: row) // super.init(row: row) is required
required init(row: Row) throws { // init(row) is required
try super.init(row: row) // super.init(row: row) is required
}
}
@@ -57,9 +57,9 @@ class RecordWithMutablePropertyAndCustomInitializer : Record {
class RecordWithImmutableProperty : Record {
let initializedFromRow: Bool
required init(row: Row) { // An initializer is required, and the minimum is init(row)
initializedFromRow = true // property must be set before super.init(row: row)
super.init(row: row) // super.init(row: row) is required
required init(row: Row) throws { // An initializer is required, and the minimum is init(row)
initializedFromRow = true // property must be set before super.init(row: row)
try super.init(row: row) // super.init(row: row) is required
}
}
@@ -72,9 +72,9 @@ class RecordWithPedigree : Record {
super.init() // super.init() is required
}
required init(row: Row) { // An initializer is required, and the minimum is init(row)
initializedFromRow = true // property must be set before super.init(row: row)
super.init(row: row) // super.init(row: row) is required
required init(row: Row) throws { // An initializer is required, and the minimum is init(row)
initializedFromRow = true // property must be set before super.init(row: row)
try super.init(row: row) // super.init(row: row) is required
}
}
@@ -87,9 +87,9 @@ class RecordWithImmutablePropertyAndCustomInitializer : Record {
super.init() // super.init() is required
}
required init(row: Row) { // An initializer is required, and the minimum is init(row)
initializedFromRow = true // property must be set before super.init(row: row)
super.init(row: row) // super.init(row: row) is required
required init(row: Row) throws { // An initializer is required, and the minimum is init(row)
initializedFromRow = true // property must be set before super.init(row: row)
try super.init(row: row) // super.init(row: row) is required
}
}
@@ -23,9 +23,9 @@ private class MinimalNonOptionalPrimaryKeySingle: Record, Hashable {
"minimalSingles"
}
required init(row: Row) {
required init(row: Row) throws {
id = row["id"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -22,9 +22,9 @@ class MinimalRowID : Record, Hashable {
"minimalRowIDs"
}
required init(row: Row) {
required init(row: Row) throws {
id = row["id"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -21,9 +21,9 @@ class MinimalSingle: Record, Hashable {
"minimalSingles"
}
required init(row: Row) {
required init(row: Row) throws {
UUID = row["UUID"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -35,12 +35,12 @@ private class Person : Record, Hashable {
"persons"
}
required init(row: Row) {
required init(row: Row) throws {
id = row[.rowID]
age = row["age"]
name = row["name"]
creationDate = row["creationDate"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -30,11 +30,11 @@ private class Citizenship : Record, Hashable {
"citizenships"
}
required init(row: Row) {
required init(row: Row) throws {
personName = row["personName"]
countryName = row["countryName"]
native = row["native"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -28,10 +28,10 @@ private class Item : Record, Hashable {
"items"
}
required init(row: Row) {
required init(row: Row) throws {
name = row["name"]
email = row["email"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -32,12 +32,12 @@ private class Person : Record, Hashable {
"persons"
}
required init(row: Row) {
required init(row: Row) throws {
id = row["id"]
age = row["age"]
name = row["name"]
creationDate = row["creationDate"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -26,10 +26,10 @@ class Pet : Record, Hashable {
"pets"
}
required init(row: Row) {
required init(row: Row) throws {
UUID = row["UUID"]
name = row["name"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -25,10 +25,10 @@ class Email : Record, Hashable {
"emails"
}
required init(row: Row) {
required init(row: Row) throws {
email = row["email"]
label = row["label"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
+6 -6
View File
@@ -31,12 +31,12 @@ private class Person : Record {
"persons"
}
required init(row: Row) {
required init(row: Row) throws {
id = row["id"]
age = row["age"]
name = row["name"]
creationDate = row["creationDate"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -65,9 +65,9 @@ private class MinimalPersonWithOverrides : Person {
// Record
required init(row: Row) {
required init(row: Row) throws {
extra = row["extra"]
super.init(row: row)
try super.init(row: row)
}
}
@@ -86,9 +86,9 @@ private class PersonWithOverrides : Person {
// Record
required init(row: Row) {
required init(row: Row) throws {
extra = row["extra"]
super.init(row: row)
try super.init(row: row)
}
override func insert(_ db: Database) throws {
@@ -23,12 +23,12 @@ class BadlyMangledStuff : Record {
"stuffs"
}
required init(row: Row) {
required init(row: Row) throws {
// Here user may peek fancy column names that match his SQL queries.
// However this is not the way to do it (see testBadlyMangledStuff()).
id = row["mangled_id"]
name = row["mangled_name"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {
@@ -207,7 +207,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
ValueObservation
.trackingConstantRegion { db in try Row.fetchOne(db, request) }
.removeDuplicates()
.map { row in row.map(ParentInfo.init(row:)) },
.map { row in try row.map(ParentInfo.init(row:)) },
records: [
nil,
ParentInfo(
@@ -312,7 +312,7 @@ class ValueObservationQueryInterfaceRequestTests: GRDBTestCase {
ValueObservation
.trackingConstantRegion { db in try Row.fetchAll(db, request) }
.removeDuplicates()
.map { rows in rows.map(ParentInfo.init(row:)) },
.map { rows in try rows.map(ParentInfo.init(row:)) },
records: [
[],
[
@@ -30,7 +30,7 @@ class FetchRecordClassTests: XCTestCase {
"item"
}
required init(row: GRDB.Row) {
required init(row: GRDB.Row) throws {
i0 = row["i0"]
i1 = row["i1"]
i2 = row["i2"]
@@ -41,7 +41,7 @@ class FetchRecordClassTests: XCTestCase {
i7 = row["i7"]
i8 = row["i8"]
i9 = row["i9"]
super.init(row: row)
try super.init(row: row)
}
}
@@ -361,7 +361,7 @@ class ItemRecord : Record {
"items"
}
required init(row: GRDB.Row) {
required init(row: GRDB.Row) throws {
i0 = row["i0"]
i1 = row["i1"]
i2 = row["i2"]
@@ -372,7 +372,7 @@ class ItemRecord : Record {
i7 = row["i7"]
i8 = row["i8"]
i9 = row["i9"]
super.init(row: row)
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) {