Skip to content

Structure

SQLRowDecoder

An implementation of Decoder designed to decode “models” (or, in general, aggregate Decodable types) from SQLRows returned from a database query.
struct SQLRowDecoder

Overview

This type essentially acts as a bridge between Codable structure types and the per-column decoding methods provided by SQLRow. It is, somewhat confusingly, designed primarily for use via SQLQueryFetcher’s all(decoding:) and first(decoding:) methods, or somewhat more directly via decode(model:prefix:keyDecodingStrategy:userInfo:) and decode(model:with:), but it can also be manually invoked. For example:

struct MySimpleUserModel: Codable {
    var id: Int
    var username: String
    var passwordHash: [UInt8]
    var email: String?
    var createdAt: Date
}

let query = sqlDatabase.select()
    .columns("id", "username", "password_hash", "email", "created_at")
    .from("my_simple_users")

// Direct usage:
let rows = try await query.all()
let decoder = SQLRowDecoder(keyDecodingStrategy: .convertFromSnakeCase)
let userModels = try rows.map { row in
    try decoder.decode(MySimpleUserModel.self, from: row)
}

// Invoked via SQLRow:
let userModels = try rows.map { row in
    try row.decode(MySimpleUserModel.self, keyDecodingStrategy: .convertFromSnakeCase)
}

// Invoked via SQLQueryFetcher:
let userModels = try await query.all(
    decoding: MySimpleUserModel.self,
    keyDecodingStrategy: .convertFromSnakeCase
)

Important

This API is designed for use with models in the generic sense, i.e. Swift structures which conform to Codable. It is not designed to bridge between FluentKit’s Model protocol and SQLKit methods; an attempt to do so will result in errors and/or unexpected behavior.

Topics

Initializers

Instance Properties

  • keyDecodingStrategy
    The key decoding strategy to use.
  • prefix
    A prefix to be applied to coding keys before interpreting them as column names.
  • userInfo
    User info to provide to the underlying Decoder.

Instance Methods

Enumerations

Relationships

Conforms To

  • Swift.Sendable
  • Swift.SendableMetatype

See Also

Data Access

  • SQLDatabase
    The common interface to SQLKit for both drivers and client code.
  • SQLRow
    Represents a single row in a result set returned from an executed SQL query.
  • SQLQueryEncoder
    An implementation of Encoder designed to encode “models” (or, in general, aggregate Encodable types) into a form which can be used as input to a database query.