SqliteProjetDao.swift 76 lignes · 2553 octets
import Foundation

struct SqliteProjetDao: ProjetDao {
    let db: SqliteDatabase

    private static let columns = """
    localId, serverId, nom, description, workflowServerId, membresJson, creePar, \
    planification, echeance, joursOuvres, createdAt, updatedAt
    """

    private static func map(_ row: SqliteRow) -> ProjetEntity {
        var e = ProjetEntity()
        e.localId = row.int64(0)
        e.serverId = row.textOrNil(1)
        e.nom = row.text(2)
        e.description = row.text(3)
        e.workflowServerId = row.text(4)
        e.membresJson = row.text(5)
        e.creePar = row.text(6)
        e.planification = row.bool(7)
        e.echeance = row.textOrNil(8)
        e.joursOuvres = row.int(9)
        e.createdAt = row.int64(10)
        e.updatedAt = row.int64(11)
        return e
    }

    @discardableResult
    func upsert(_ entity: ProjetEntity) async throws -> Int64 {
        try await db.insert(
            "INSERT OR REPLACE INTO projets (\(Self.columns)) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            [
                .rowId(entity.localId),
                .optText(entity.serverId),
                .text(entity.nom),
                .text(entity.description),
                .text(entity.workflowServerId),
                .text(entity.membresJson),
                .text(entity.creePar),
                .bool(entity.planification),
                .optText(entity.echeance),
                .int(Int64(entity.joursOuvres)),
                .int(entity.createdAt),
                .int(entity.updatedAt),
            ]
        )
    }

    func getByServerId(_ serverId: String) async throws -> ProjetEntity? {
        try await db.query(
            "SELECT \(Self.columns) FROM projets WHERE serverId = ?",
            [.text(serverId)],
            map: Self.map
        ).first
    }

    func getByLocalId(_ localId: Int64) async throws -> ProjetEntity? {
        try await db.query(
            "SELECT \(Self.columns) FROM projets WHERE localId = ?",
            [.int(localId)],
            map: Self.map
        ).first
    }

    func deleteByServerId(_ serverId: String) async throws {
        try await db.write("DELETE FROM projets WHERE serverId = ?", [.text(serverId)])
    }

    func listAll() async throws -> [ProjetEntity] {
        try await db.query("SELECT \(Self.columns) FROM projets", map: Self.map)
    }

    func fetchAll() async throws -> [ProjetEntity] {
        try await db.query("SELECT \(Self.columns) FROM projets ORDER BY nom ASC", map: Self.map)
    }
}