fix(CF-352): Auto-create session in sessionCommitLink to prevent FK constraint error
- Check if session exists before inserting commit link - Auto-create minimal session record if missing (status=active, no project) - Prevents FK constraint violation when cache/DB drift occurs - Return message indicates if session was auto-created for monitoring - Handles edge cases: concurrent calls, missing committed_at, NULL project Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -407,6 +407,24 @@ export async function sessionCommitLink(
|
|||||||
commit_message: string | null,
|
commit_message: string | null,
|
||||||
committed_at: string | null
|
committed_at: string | null
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
|
// Check if session exists
|
||||||
|
const sessionExists = await queryOne<{ exists: boolean }>(
|
||||||
|
'SELECT EXISTS(SELECT 1 FROM sessions WHERE id = $1) as exists',
|
||||||
|
[session_id]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Auto-create session if missing (prevents FK constraint error)
|
||||||
|
if (!sessionExists?.exists) {
|
||||||
|
const timestamp = committed_at || new Date().toISOString();
|
||||||
|
await execute(
|
||||||
|
`INSERT INTO sessions (id, started_at, status)
|
||||||
|
VALUES ($1, $2, 'active')
|
||||||
|
ON CONFLICT (id) DO NOTHING`,
|
||||||
|
[session_id, timestamp]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now safely insert commit link
|
||||||
await execute(
|
await execute(
|
||||||
`INSERT INTO session_commits (session_id, commit_sha, repo, commit_message, committed_at)
|
`INSERT INTO session_commits (session_id, commit_sha, repo, commit_message, committed_at)
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
@@ -414,5 +432,6 @@ export async function sessionCommitLink(
|
|||||||
[session_id, commit_sha, repo, commit_message, committed_at]
|
[session_id, commit_sha, repo, commit_message, committed_at]
|
||||||
);
|
);
|
||||||
|
|
||||||
return `Linked commit ${commit_sha.substring(0, 7)} to session ${session_id}`;
|
const prefix = sessionExists?.exists ? '' : '[auto-created session] ';
|
||||||
|
return `${prefix}Linked commit ${commit_sha.substring(0, 7)} to session ${session_id}`;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user