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
init(prefix:keyDecodingStrategy:userInfo:)Create a configuredSQLRowDecoder.
Instance Properties
keyDecodingStrategyThe key decoding strategy to use.prefixA prefix to be applied to coding keys before interpreting them as column names.userInfoUser info to provide to the underlyingDecoder.
Instance Methods
decode(_:from:)Decode a value of typeTfrom the givenSQLRow.
Enumerations
SQLRowDecoder.KeyDecodingStrategyA strategy describing how to transform column names in a row to match the expectations of decoded type(s).
Relationships
Conforms To
Swift.SendableSwift.SendableMetatype
See Also
Data Access
SQLDatabaseThe common interface to SQLKit for both drivers and client code.SQLRowRepresents a single row in a result set returned from an executed SQL query.SQLQueryEncoderAn implementation ofEncoderdesigned to encode “models” (or, in general, aggregateEncodabletypes) into a form which can be used as input to a database query.