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.makeSelectStatement(sql: "SELECT ...")
try Player.fetchCursor(statement, arguments:...) // Cursor of Player
try Player.fetchAll(statement, arguments:...)    // [Player]
try Player.fetchOne(statement, arguments:...)    // Player?

FetchableRecord is adopted by Record.

  • init(row:) Default implementation

    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().

    Default Implementation

    Declaration

    Swift

    init(row: Row)
  • databaseDecodingUserInfo Default implementation

    When 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 implementation

    When 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 }
  • 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 dispath 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 the TableRecord.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 the TableRecord.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
    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 the TableRecord.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.

  • fetchCursor(_:keys:) Extension method

    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(_:keys:) Extension method

    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(_:key:) Extension method

    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(_:keys:) Extension method

    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(_:keys:) Extension method

    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(_:key:) Extension method

    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.

  • A cursor over records fetched from a prepared statement.

    let statement = try db.makeSelectStatement(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 dispath queue.

    Throws

    A DatabaseError is thrown whenever an SQLite error occurs.

    Declaration

    Swift

    public static func fetchCursor(
        _ statement: SelectStatement,
        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.

  • Returns an array of records fetched from a prepared statement.

    let statement = try db.makeSelectStatement(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: SelectStatement,
        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.

  • Returns a single record fetched from a prepared statement.

    let statement = try db.makeSelectStatement(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: SelectStatement,
        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.

  • 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 dispath 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.

  • 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.

  • 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 dispath 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.