FetchableRecord
public protocol FetchableRecord
Types that adopt FetchableRecord
can be initialized from a database Row.
let row = try Row.fetchOne(db, sql: "SELECT ...")!
let player = Player(row)
The protocol comes with built-in methods that allow to fetch cursors, arrays, or single records:
try Player.fetchCursor(db, sql: "SELECT ...", arguments:...) // Cursor of Player
try Player.fetchAll(db, sql: "SELECT ...", arguments:...) // [Player]
try Player.fetchOne(db, sql: "SELECT ...", arguments:...) // Player?
let statement = try db.makeStatement(sql: "SELECT ...")
try Player.fetchCursor(statement, arguments:...) // Cursor of Player
try Player.fetchAll(statement, arguments:...) // [Player]
try Player.fetchOne(statement, arguments:...) // Player?
-
Creates a record from
row
.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()
.Declaration
Swift
init(row: Row)
-
databaseDecodingUserInfo
Default implementationWhen the FetchableRecord type also adopts the standard Decodable protocol, you can use this dictionary to customize the decoding process from database rows.
For example:
// A key that holds a decoder's name let decoderName = CodingUserInfoKey(rawValue: "decoderName")! // A FetchableRecord + Decodable record struct Player: FetchableRecord, Decodable { // Customize the decoder name when decoding a database row static let databaseDecodingUserInfo: [CodingUserInfoKey: Any] = [decoderName: "Database"] init(from decoder: Decoder) throws { // Print the decoder name print(decoder.userInfo[decoderName]) ... } } // prints "Database" let player = try Player.fetchOne(db, ...) // prints "JSON" let decoder = JSONDecoder() decoder.userInfo = [decoderName: "JSON"] let player = try decoder.decode(Player.self, from: ...)
Default Implementation
Declaration
Swift
static var databaseDecodingUserInfo: [CodingUserInfoKey : Any] { get }
-
databaseJSONDecoder(for:
Default implementation) When the FetchableRecord type also adopts the standard Decodable protocol, this method controls the decoding process of nested properties from JSON database columns.
The default implementation returns a JSONDecoder with the following properties:
- dataDecodingStrategy: .base64
- dateDecodingStrategy: .millisecondsSince1970
- nonConformingFloatDecodingStrategy: .throw
You can override those defaults:
struct Achievement: Decodable { var name: String var date: Date } struct Player: Decodable, FetchableRecord { // stored in a JSON column var achievements: [Achievement] static func databaseJSONDecoder(for column: String) -> JSONDecoder { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 return decoder } }
Default Implementation
Returns a JSONDecoder with the following properties:
- dataDecodingStrategy: .base64
- dateDecodingStrategy: .millisecondsSince1970
- nonConformingFloatDecodingStrategy: .throw
Declaration
Swift
static func databaseJSONDecoder(for column: String) -> JSONDecoder
-
databaseDateDecodingStrategy
Default implementationWhen the FetchableRecord type also adopts the standard Decodable protocol, this property controls the decoding of date properties.
Default value is .deferredToDate
For example:
struct Player: FetchableRecord, Decodable { static let databaseDateDecodingStrategy: DatabaseDateDecodingStrategy = .timeIntervalSince1970 var name: String var registrationDate: Date // decoded from epoch timestamp }
Default Implementation
Declaration
Swift
static var databaseDateDecodingStrategy: DatabaseDateDecodingStrategy { get }
-
databaseColumnDecodingStrategy
Default implementationWhen the FetchableRecord type also adopts the standard Decodable protocol, this property controls the key decoding strategy.
Default value is .useDefaultKeys
For example:
struct Player: FetchableRecord, Decodable { static let databaseDateDecodingStrategy: DatabaseColumnDecodingStrategy = .convertFromSnakeCase var playerID: String // decoded from player_id }
Default Implementation
Declaration
Swift
static var databaseColumnDecodingStrategy: DatabaseColumnDecodingStrategy { get }
-
fetchCursor(_:
Extension methodarguments: adapter: ) A cursor over records fetched from a prepared statement.
let statement = try db.makeStatement(sql: "SELECT * FROM player") let players = try Player.fetchCursor(statement) // Cursor of Player while let player = try players.next() { // Player ... }
If the database is modified during the cursor iteration, the remaining elements are undefined.
The cursor must be iterated in a protected dispatch queue.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchCursor( _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
Parameters
statement
The statement to run.
arguments
Optional statement arguments.
adapter
Optional RowAdapter
Return Value
A cursor over fetched records.
-
fetchAll(_:
Extension methodarguments: adapter: ) Returns an array of records fetched from a prepared statement.
let statement = try db.makeStatement(sql: "SELECT * FROM player") let players = try Player.fetchAll(statement) // [Player]
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchAll( _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> [Self]
Parameters
statement
The statement to run.
arguments
Optional statement arguments.
adapter
Optional RowAdapter
Return Value
An array of records.
-
fetchOne(_:
Extension methodarguments: adapter: ) Returns a single record fetched from a prepared statement.
let statement = try db.makeStatement(sql: "SELECT * FROM player") let player = try Player.fetchOne(statement) // Player?
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchOne( _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Self?
Parameters
statement
The statement to run.
arguments
Optional statement arguments.
adapter
Optional RowAdapter
Return Value
An optional record.
-
fetchCursor(_:
Extension methodsql: arguments: adapter: ) Returns a cursor over records fetched from an SQL query.
let players = try Player.fetchCursor(db, sql: "SELECT * FROM player") // Cursor of Player while let player = try players.next() { // Player ... }
If the database is modified during the cursor iteration, the remaining elements are undefined.
The cursor must be iterated in a protected dispatch queue.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchCursor( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> RecordCursor<Self>
Parameters
db
A database connection.
sql
An SQL query.
arguments
Statement arguments.
adapter
Optional RowAdapter
Return Value
A cursor over fetched records.
-
fetchAll(_:
Extension methodsql: arguments: adapter: ) Returns an array of records fetched from an SQL query.
let players = try Player.fetchAll(db, sql: "SELECT * FROM player") // [Player]
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchAll( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> [Self]
Parameters
db
A database connection.
sql
An SQL query.
arguments
Statement arguments.
adapter
Optional RowAdapter
Return Value
An array of records.
-
fetchOne(_:
Extension methodsql: arguments: adapter: ) Returns a single record fetched from an SQL query.
let player = try Player.fetchOne(db, sql: "SELECT * FROM player") // Player?
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchOne( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Self?
Parameters
db
A database connection.
sql
An SQL query.
arguments
Statement arguments.
adapter
Optional RowAdapter
Return Value
An optional record.
-
fetchCursor(_:
Extension method_: ) Returns a cursor over records fetched from a fetch request.
let request = try Player.all() let players = try Player.fetchCursor(db, request) // Cursor of Player while let player = try players.next() { // Player ... }
If the database is modified during the cursor iteration, the remaining elements are undefined.
The cursor must be iterated in a protected dispatch queue.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchCursor<R>(_ db: Database, _ request: R) throws -> RecordCursor<Self> where R : FetchRequest
Parameters
db
A database connection.
sql
a FetchRequest.
Return Value
A cursor over fetched records.
-
fetchAll(_:
Extension method_: ) Returns an array of records fetched from a fetch request.
let request = try Player.all() let players = try Player.fetchAll(db, request) // [Player]
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchAll<R>(_ db: Database, _ request: R) throws -> [Self] where R : FetchRequest
Parameters
db
A database connection.
sql
a FetchRequest.
Return Value
An array of records.
-
fetchOne(_:
Extension method_: ) Returns a single record fetched from a fetch request.
let request = try Player.filter(key: 1) let player = try Player.fetchOne(db, request) // Player?
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchOne<R>(_ db: Database, _ request: R) throws -> Self? where R : FetchRequest
Parameters
db
A database connection.
sql
a FetchRequest.
Return Value
An optional record.
-
fetchCursor(_:
Extension method) A cursor over all records fetched from the database.
// SELECT * FROM player let players = try Player.fetchCursor(db) // Cursor of Player while let player = try players.next() { // Player ... }
Records are iterated in the natural ordering of the table.
If the database is modified during the cursor iteration, the remaining elements are undefined.
The cursor must be iterated in a protected dispatch queue.
The selection defaults to all columns. This default can be changed for all requests by the
TableRecord.databaseSelection
property, or for individual requests with theTableRecord.select
method.Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchCursor(_ db: Database) throws -> RecordCursor<Self>
Parameters
db
A database connection.
Return Value
A cursor over fetched records.
-
fetchAll(_:
Extension method) An array of all records fetched from the database.
// SELECT * FROM player let players = try Player.fetchAll(db) // [Player]
The selection defaults to all columns. This default can be changed for all requests by the
TableRecord.databaseSelection
property, or for individual requests with theTableRecord.select
method.Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchAll(_ db: Database) throws -> [Self]
Parameters
db
A database connection.
-
fetchOne(_:
Extension method) The first found record.
// SELECT * FROM player LIMIT 1 let player = try Player.fetchOne(db) // Player?
The selection defaults to all columns. This default can be changed for all requests by the
TableRecord.databaseSelection
property, or for individual requests with theTableRecord.select
method.Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchOne(_ db: Database) throws -> Self?
Parameters
db
A database connection.
-
fetchSet(_:
Extension method) A set of all records fetched from the database.
// SELECT * FROM player let players = try Player.fetchSet(db) // Set<Player>
The selection defaults to all columns. This default can be changed for all requests by the
TableRecord.databaseSelection
property, or for individual requests with theTableRecord.select
method.Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchSet(_ db: Database) throws -> Set<Self>
Parameters
db
A database connection.
-
fetchCursor(_:
Extension methodkeys: ) Returns a cursor over records, given their primary keys.
let players = try Player.fetchCursor(db, keys: [1, 2, 3]) // Cursor of Player while let player = try players.next() { // Player ... }
Records are iterated in unspecified order.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchCursor<Sequence>(_ db: Database, keys: Sequence) throws -> RecordCursor<Self> where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible
Parameters
db
A database connection.
keys
A sequence of primary keys.
Return Value
A cursor over fetched records.
-
fetchAll(_:
Extension methodkeys: ) Returns an array of records, given their primary keys.
let players = try Player.fetchAll(db, keys: [1, 2, 3]) // [Player]
The order of records in the returned array is undefined.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchAll<Sequence>(_ db: Database, keys: Sequence) throws -> [Self] where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible
Parameters
db
A database connection.
keys
A sequence of primary keys.
Return Value
An array of records.
-
fetchOne(_:
Extension methodkey: ) Returns a single record given its primary key.
let player = try Player.fetchOne(db, key: 123) // Player?
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchOne<PrimaryKeyType>(_ db: Database, key: PrimaryKeyType?) throws -> Self? where PrimaryKeyType: DatabaseValueConvertible
Parameters
db
A database connection.
key
A primary key value.
Return Value
An optional record.
-
fetchCursor(_:
Extension methodids: ) Returns a cursor over records, given their primary keys.
let players = try Player.fetchCursor(db, ids: [1, 2, 3]) // Cursor of Player while let player = try players.next() { // Player ... }
Records are iterated in unspecified order.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchCursor<Collection>(_ db: Database, ids: Collection) throws -> RecordCursor<Self> where Collection: Swift.Collection, Collection.Element == ID
Parameters
db
A database connection.
ids
A collection of primary keys.
Return Value
A cursor over fetched records.
-
fetchAll(_:
Extension methodids: ) Returns an array of records, given their primary keys.
let players = try Player.fetchAll(db, ids: [1, 2, 3]) // [Player]
The order of records in the returned array is undefined.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchAll<Collection>(_ db: Database, ids: Collection) throws -> [Self] where Collection: Swift.Collection, Collection.Element == ID
Parameters
db
A database connection.
ids
A collection of primary keys.
Return Value
An array of records.
-
fetchOne(_:
Extension methodid: ) Returns a single record given its primary key.
let player = try Player.fetchOne(db, id: 123) // Player?
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchOne(_ db: Database, id: ID) throws -> Self?
Parameters
db
A database connection.
id
A primary key value.
Return Value
An optional record.
-
fetchCursor(_:
Extension methodids: ) Returns a cursor over records, given their primary keys.
let players = try Player.fetchCursor(db, ids: [1, 2, 3]) // Cursor of Player while let player = try players.next() { // Player ... }
Records are iterated in unspecified order.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchCursor<Collection>(_ db: Database, ids: Collection) throws -> RecordCursor<Self> where Collection: Swift.Collection, Collection.Element == ID.Wrapped
Parameters
db
A database connection.
ids
A collection of primary keys.
Return Value
A cursor over fetched records.
-
fetchAll(_:
Extension methodids: ) Returns an array of records, given their primary keys.
let players = try Player.fetchAll(db, ids: [1, 2, 3]) // [Player]
The order of records in the returned array is undefined.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchAll<Collection>(_ db: Database, ids: Collection) throws -> [Self] where Collection: Swift.Collection, Collection.Element == ID.Wrapped
Parameters
db
A database connection.
ids
A collection of primary keys.
Return Value
An array of records.
-
fetchOne(_:
Extension methodid: ) Returns a single record given its primary key.
let player = try Player.fetchOne(db, id: 123) // Player?
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchOne(_ db: Database, id: ID.Wrapped) throws -> Self?
Parameters
db
A database connection.
id
A primary key value.
Return Value
An optional record.
-
fetchSet(_:
Extension methodkeys: ) Returns a set of records, given their primary keys.
let players = try Player.fetchSet(db, keys: [1, 2, 3]) // Set<Player>
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchSet<Sequence>(_ db: Database, keys: Sequence) throws -> Set<Self> where Sequence: Swift.Sequence, Sequence.Element: DatabaseValueConvertible
Parameters
db
A database connection.
keys
A sequence of primary keys.
Return Value
A set of records.
-
fetchSet(_:
Extension methodids: ) Returns a set of records, given their primary keys.
let players = try Player.fetchSet(db, ids: [1, 2, 3]) // Set<Player>
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchSet<Collection>(_ db: Database, ids: Collection) throws -> Set<Self> where Collection: Swift.Collection, Collection.Element == ID
Parameters
db
A database connection.
ids
A collection of primary keys.
Return Value
A set of records.
Available where Self
: TableRecord
& Hashable
& Identifiable
, ID
: _OptionalProtocol
, ID.Wrapped
: DatabaseValueConvertible
-
fetchSet(_:
Extension methodids: ) Returns a set of records, given their primary keys.
let players = try Player.fetchSet(db, ids: [1, 2, 3]) // Set<Player>
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchSet<Collection>(_ db: Database, ids: Collection) throws -> Set<Self> where Collection: Swift.Collection, Collection.Element == ID.Wrapped
Parameters
db
A database connection.
ids
A collection of primary keys.
Return Value
A set of records.
-
fetchCursor(_:
Extension methodkeys: ) Returns a cursor over records identified by the provided unique keys (primary key or any key with a unique index on it).
// Cursor of Player let players = try Player.fetchCursor(db, keys: [ ["email": "a@example.com"], ["email": "b@example.com"]]) while let player = try players.next() { // Player ... }
Records are iterated in unspecified order.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchCursor(_ db: Database, keys: [[String: DatabaseValueConvertible?]]) throws -> RecordCursor<Self>
Parameters
db
A database connection.
keys
An array of key dictionaries.
Return Value
A cursor over fetched records.
-
fetchAll(_:
Extension methodkeys: ) Returns an array of records identified by the provided unique keys (primary key or any key with a unique index on it).
// [Player] let players = try Player.fetchAll(db, keys: [ ["email": "a@example.com"], ["email": "b@example.com"]])
The order of records in the returned array is undefined.
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchAll(_ db: Database, keys: [[String : DatabaseValueConvertible?]]) throws -> [Self]
Parameters
db
A database connection.
keys
An array of key dictionaries.
Return Value
An array of records.
-
fetchOne(_:
Extension methodkey: ) Returns a single record identified by a unique key (the primary key or any key with a unique index on it).
let player = try Player.fetchOne(db, key: ["name": Arthur"]) // Player?
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchOne(_ db: Database, key: [String : DatabaseValueConvertible?]?) throws -> Self?
Parameters
db
A database connection.
key
A dictionary of values.
Return Value
An optional record.
-
fetchSet(_:
Extension methodkeys: ) Returns a set of records identified by the provided unique keys (primary key or any key with a unique index on it).
// Set<Player> let players = try Player.fetchSet(db, keys: [ ["email": "a@example.com"], ["email": "b@example.com"]])
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchSet(_ db: Database, keys: [[String : DatabaseValueConvertible?]]) throws -> Set<Self>
Parameters
db
A database connection.
keys
An array of key dictionaries.
Return Value
A set of records.
-
fetchSet(_:
Extension methodarguments: adapter: ) Returns a set of records fetched from a prepared statement.
let statement = try db.makeStatement(sql: "SELECT * FROM player") let players = try Player.fetchSet(statement) // Set<Player>
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchSet( _ statement: Statement, arguments: StatementArguments? = nil, adapter: RowAdapter? = nil) throws -> Set<Self>
Parameters
statement
The statement to run.
arguments
Optional statement arguments.
adapter
Optional RowAdapter
Return Value
A set of records.
-
fetchSet(_:
Extension methodsql: arguments: adapter: ) Returns a set of records fetched from an SQL query.
let players = try Player.fetchSet(db, sql: "SELECT * FROM player") // Set<Player>
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchSet( _ db: Database, sql: String, arguments: StatementArguments = StatementArguments(), adapter: RowAdapter? = nil) throws -> Set<Self>
Parameters
db
A database connection.
sql
An SQL query.
arguments
Statement arguments.
adapter
Optional RowAdapter
Return Value
A set of records.
-
fetchSet(_:
Extension method_: ) Returns a set of records fetched from a fetch request.
let request = try Player.all() let players = try Player.fetchSet(db, request) // Set<Player>
Throws
A DatabaseError is thrown whenever an SQLite error occurs.Declaration
Swift
public static func fetchSet<R>(_ db: Database, _ request: R) throws -> Set<Self> where R : FetchRequest
Parameters
db
A database connection.
sql
a FetchRequest.
Return Value
A set of records.