SqliteIndisponibiliteDao.swift 68 lignes · 2359 octets
import Foundation

struct SqliteIndisponibiliteDao: IndisponibiliteDao {
    let db: SqliteDatabase

    private static let columns = """
    localId, serverId, cibleType, cibleId, debutMs, finMs, nature, commentaire, \
    updatedAt, calendarEventId
    """

    private static func map(_ row: SqliteRow) -> IndisponibiliteEntity {
        var e = IndisponibiliteEntity()
        e.localId = row.int64(0)
        e.serverId = row.textOrNil(1)
        e.cibleType = row.text(2)
        e.cibleId = row.text(3)
        e.debutMs = row.int64(4)
        e.finMs = row.int64(5)
        e.nature = row.textOrNil(6)
        e.commentaire = row.textOrNil(7)
        e.updatedAt = row.int64(8)
        e.calendarEventId = row.int64OrNil(9)
        return e
    }

    @discardableResult
    func upsert(_ entity: IndisponibiliteEntity) async throws -> Int64 {
        try await db.insert(
            "INSERT OR REPLACE INTO indisponibilites (\(Self.columns)) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            [
                .rowId(entity.localId),
                .optText(entity.serverId),
                .text(entity.cibleType),
                .text(entity.cibleId),
                .int(entity.debutMs),
                .int(entity.finMs),
                .optText(entity.nature),
                .optText(entity.commentaire),
                .int(entity.updatedAt),
                .optInt(entity.calendarEventId),
            ]
        )
    }

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

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

    func listByCible(cibleType: String, cibleId: String) async throws -> [IndisponibiliteEntity] {
        try await db.query(
            "SELECT \(Self.columns) FROM indisponibilites WHERE cibleType = ? AND cibleId = ?",
            [.text(cibleType), .text(cibleId)],
            map: Self.map
        )
    }

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