-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruns.ts
More file actions
76 lines (69 loc) · 2.54 KB
/
runs.ts
File metadata and controls
76 lines (69 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import { getDb } from './database';
import type { AnalysisRun, RunWithStats } from '$shared/types';
export function createRun(
sourcePath: string,
model: string,
minConfidence: number,
locationId?: number | null,
settingsJson?: string | null,
): AnalysisRun {
const db = getDb();
const stmt = db.prepare(`
INSERT INTO analysis_runs (location_id, source_path, model, min_confidence, settings_json, status, started_at)
VALUES (?, ?, ?, ?, ?, 'running', datetime('now'))
`);
const result = stmt.run(locationId ?? null, sourcePath, model, minConfidence, settingsJson ?? null);
return getRunById(result.lastInsertRowid as number)!;
}
export function updateRunStatus(id: number, status: AnalysisRun['status']): void {
const db = getDb();
if (status === 'completed' || status === 'failed') {
db.prepare("UPDATE analysis_runs SET status = ?, completed_at = datetime('now') WHERE id = ?").run(status, id);
} else {
db.prepare('UPDATE analysis_runs SET status = ? WHERE id = ?').run(status, id);
}
}
function getRunById(id: number): AnalysisRun | undefined {
const db = getDb();
return db.prepare('SELECT * FROM analysis_runs WHERE id = ?').get(id) as AnalysisRun | undefined;
}
export function findCompletedRuns(sourcePath: string, model: string): AnalysisRun[] {
const db = getDb();
return db
.prepare(
"SELECT * FROM analysis_runs WHERE source_path = ? AND model = ? AND status = 'completed' ORDER BY completed_at DESC",
)
.all(sourcePath, model) as AnalysisRun[];
}
export function deleteRun(id: number): void {
const db = getDb();
db.transaction(() => {
db.prepare('DELETE FROM detections WHERE run_id = ?').run(id);
db.prepare('DELETE FROM analysis_runs WHERE id = ?').run(id);
})();
}
/** Mark any runs left in 'running' state as 'failed' — they are stale from a previous session. */
export function markStaleRunsAsFailed(): number {
const db = getDb();
const result = db
.prepare("UPDATE analysis_runs SET status = 'failed', completed_at = datetime('now') WHERE status = 'running'")
.run();
return result.changes;
}
export function getRunsWithStats(): RunWithStats[] {
const db = getDb();
return db
.prepare(
`SELECT
r.*,
COALESCE(d.cnt, 0) AS detection_count,
l.name AS location_name
FROM analysis_runs r
LEFT JOIN (
SELECT run_id, COUNT(*) AS cnt FROM detections GROUP BY run_id
) d ON d.run_id = r.id
LEFT JOIN locations l ON l.id = r.location_id
ORDER BY r.started_at DESC`,
)
.all() as RunWithStats[];
}