Structure
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.struct SQLQueryEncoder
Overview
At present, there is no “input”-capable equivalent of an SQLRow, so this encoder returns a somewhat awkward array of “column name”/“value expression” pairs.
This type is, somewhat confusingly, designed primarily for use with methods such as
It can also be manually invoked. For example:
struct MySimpleUserModel: Codable {
var id: Int? = nil
var username: String
var passwordHash: [UInt8]
var email: String?
var createdAt: Date
}
let users: [MySimpleUserModel] = [
.init(username: "johndoe", passwordHash: (0..<32).random(in: .min ... .max), email: "foo@bar.com", createdAt: .init()),
.init(username: "janedoe", passwordHash: (0..<32).random(in: .min ... .max), email: nil, createdAt: .init()),
]
// Direct usage (not recommended):
let encoder = SQLQueryEncoder(keyEncodingStrategy: .convertToSnakeCase, nilEncodingStrategy: .asNil)
let rows = try users.map { user in try encoder.encode(user) }
let query = sqlDatabase
.insert(into: "my_simple_users")
.columns(rows[0].map(\.0))
for row in rows {
query.values(row.map(\.1))
}
try await query.run()
// Invoked via SQLInsertBuilder and SQLConflictUpdateBuilder:
let encoder = SQLQueryEncoder(keyEncodingStrategy: .convertToSnakeCase, nilEncodingStrategy: .asNil)
try await sqlDatabase.insert(into: "my_simple_users")
.models(users, with: encoder)
.onConflict { $0.set(excludedContentOf: users[0], with: encoder) }
.run()
// Invoked via SQLUpdateBuilder:
try await sqlDatabase.update("my_simple_users")
.set(model: users[0], keyEncodingStrategy: .convertToSnakeCase, nilEncodingStrategy: .asNil)
.where("id", .equal, SQLBind(1))
.run()
Topics
Initializers
init(prefix:keyEncodingStrategy:nilEncodingStrategy:userInfo:)Create a configuredSQLQueryEncoder.
Instance Properties
keyEncodingStrategyThe key encoding strategy to use.nilEncodingStrategyThenilvalue encoding strategy to use.prefixA prefix to be added to keys when encoding column names.userInfoUser info to provide to the underlyingEncoder.
Instance Methods
encode(_:)Encode anEncodablevalue to an array of key/expression pairs suitable for use as input tovalues(_:),set(_:to:), and other related APIs.
Enumerations
SQLQueryEncoder.KeyEncodingStrategyA strategy describing how to transform individual keys into encoded column names.SQLQueryEncoder.NilEncodingStrategyA strategy describing the desired encoding ofnilinput values.
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.SQLRowDecoderAn implementation ofDecoderdesigned to decode “models” (or, in general, aggregateDecodabletypes) fromSQLRows returned from a database query.