Skip to content

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

Instance Properties

Instance Methods

  • encode(_:)
    Encode an Encodable value to an array of key/expression pairs suitable for use as input to values(_:), set(_:to:), and other related APIs.

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.
  • SQLRowDecoder
    An implementation of Decoder designed to decode “models” (or, in general, aggregate Decodable types) from SQLRows returned from a database query.