使用 Swift GRDB 中的 encode(to:) 方法可以将 Swift 对象编码为 SQL 语句并存储到数据库中。如果需要将对象的 primaryKey 设置为自增,可以使用以下代码:

struct Person: Codable, FetchableRecord, MutablePersistableRecord {
    var id: Int64?
    var name: String

    static let databaseTableName = "persons"
    static let idKey = "id"

    mutating func encode(to container: inout PersistenceContainer) {
        container[idKey] = id
        container["name"] = name
        if id == nil {
            container[idKey] = nil // Make sure NULL is inserted
        }
    }

    // Define how to create a person from a database row
    init(row: Row) {
        id = row[Person.idKey]
        name = row["name"]
    }

    // Define how to insert a person into the database
    func insert(_ db: Database) throws {
        try db.execute(
            sql: "INSERT INTO persons (name) VALUES (?)",
            arguments: [name])
        id = db.lastInsertedRowID
    }
}

在这个例子中,我们定义了一个名为 Person 的结构体,它遵循了 CodableFetchableRecordMutablePersistableRecord 协议。id 属性是可选的,因为它将在数据库中自动增长。在 encode(to:) 方法中,我们将 idname 属性绑定到 container 中。如果 id 为空,则将其设置为 nil 以确保 NULL 被插入。在 insert(_:) 方法中,我们使用 db.execute 方法将 Person 对象插入到数据库中,并将自增长的 id 设置为 lastInsertedRowID 属性的值。

在使用 Person 对象时,我们可以像这样插入一个新的记录:

var person = Person(name: "John")
try person.insert(db)

此时,数据库会自动为 id 属性分配一个自增长的值。如果我们想更新一个现有的 Person 对象,我们可以像这样做:

person.name = "Jane"
try person.update(db)

在这种情况下,id 属性将保持不变,因为它是一个主键并且不应该被修改。

Swift GRDB: 如何使用 encode(to:) 方法绑定主键并自增

原文地址: https://www.cveoy.top/t/topic/oR9D 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录