Files
sharepoint-acc-sync/src/lib/server/adapters/sqlite/run-repository.ts
2026-10-22 22:32:35 -05:00

72 lines
1.9 KiB
TypeScript

import { and, asc, desc, eq, gte, lt } from 'drizzle-orm';
import type { RunCounts, RunEvent, RunOutcome, RunRecord, RunTrigger } from '../../sync/core/model';
import type { RunRepository } from '../../sync/core/ports';
import type { Db } from './database';
import { runEvents, runs } from './schema';
type RunRow = typeof runs.$inferSelect;
export class SqliteRunRepository implements RunRepository {
constructor(private readonly db: Db) {}
async start(projectId: string, trigger: RunTrigger, at: Date): Promise<string> {
const id = crypto.randomUUID();
this.db.insert(runs).values({ id, projectId, trigger, startedAt: at }).run();
return id;
}
async finish(
runId: string,
result: { finishedAt: Date; outcome: RunOutcome; error: string | null; counts: RunCounts }
): Promise<void> {
const { finishedAt, outcome, error, counts } = result;
this.db
.update(runs)
.set({ finishedAt, outcome, error, ...counts })
.where(eq(runs.id, runId))
.run();
}
async addEvent(event: RunEvent): Promise<void> {
this.db.insert(runEvents).values(event).run();
}
async listSince(projectId: string, since: Date): Promise<RunRecord[]> {
return this.db
.select()
.from(runs)
.where(and(eq(runs.projectId, projectId), gte(runs.startedAt, since)))
.orderBy(desc(runs.startedAt))
.all()
.map(toRunRecord);
}
async listEvents(runId: string): Promise<RunEvent[]> {
return this.db
.select()
.from(runEvents)
.where(eq(runEvents.runId, runId))
.orderBy(asc(runEvents.id))
.all()
.map(({ id, ...event }) => event);
}
async pruneBefore(cutoff: Date): Promise<number> {
return this.db.delete(runs).where(lt(runs.startedAt, cutoff)).run().changes;
}
}
function toRunRecord(row: RunRow): RunRecord {
const { id, projectId, trigger, startedAt, finishedAt, outcome, error, ...counts } = row;
return {
runId: id,
projectId,
trigger,
startedAt,
finishedAt,
outcome,
error,
counts
};
}