MutablePersistableRecord

A type that can be persisted in the database, and mutates on insertion.

MutablePersistableRecord.swift:126
protocol MutablePersistableRecord : EncodableRecord, TableRecord
Browse conforming types

Overview

A MutablePersistableRecord instance mutates on insertion. This protocol is suited for record types that are a struct, and target a database table where ids are generated on insertion. Such records implement the didInsert(_:) callback in order to grab this id. For example:

// CREATE TABLE player (
//   id INTEGER PRIMARY KEY AUTOINCREMENT,
//   name TEXT NOT NULL,
//   score INTEGER NOT NULL
// )
struct Player: Encodable {
    var id: Int64?
    var name: String
    var score: Int
}

extension Player: MutablePersistableRecord {
    mutating func didInsert(_ inserted: InsertionSuccess) {
        id = inserted.rowID
    }
}

try dbQueue.write { db in
    var player = Player(id: nil, name:: "Arthur", score: 1000)
    try player.insert(db)
    print(player.id) // Some id that is not nil
}

Other record types (classes, and generally records that do not mutate on insertion) should prefer the PersistableRecord protocol instead.

Conforming to the MutablePersistableRecord Protocol

To conform to MutablePersistableRecord, provide an implementation for the encode(to:) method. This implementation is ready-made for Encodable types.

You configure the database table where records are persisted with the TableRecord inherited protocol.

Testing if a Record Exists in the Database

Inserting a Record

Inserting a Record and Fetching the Inserted Row

Updating a Record

See inherited TableRecord methods for batch updates.

Updating a Record and Fetching the Updated Row

Saving a Record

Saving a Record and Fetching the Saved Row

Deleting a Record

See inherited TableRecord methods for batch deletes.

Persistence Callbacks

Configuring Persistence