SqliteEntrepriseDao.swift 59 lignes · 1913 octets
import Foundation

struct SqliteEntrepriseDao: EntrepriseDao {
    let db: SqliteDatabase

    private static let columns = "localId, serverId, nom, secteur, creePar, createdAt, updatedAt"

    private static func map(_ row: SqliteRow) -> EntrepriseEntity {
        var e = EntrepriseEntity()
        e.localId = row.int64(0)
        e.serverId = row.textOrNil(1)
        e.nom = row.text(2)
        e.secteur = row.text(3)
        e.creePar = row.text(4)
        e.createdAt = row.int64(5)
        e.updatedAt = row.int64(6)
        return e
    }

    @discardableResult
    func upsert(_ entity: EntrepriseEntity) async throws -> Int64 {
        try await db.insert(
            "INSERT OR REPLACE INTO entreprises (\(Self.columns)) VALUES (?, ?, ?, ?, ?, ?, ?)",
            [
                .rowId(entity.localId),
                .optText(entity.serverId),
                .text(entity.nom),
                .text(entity.secteur),
                .text(entity.creePar),
                .int(entity.createdAt),
                .int(entity.updatedAt),
            ]
        )
    }

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

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

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

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