Files
opencode-manager/backend/src/db/queries.ts
T

375 lines
13 KiB
TypeScript

import type { Database } from 'bun:sqlite'
import type { Repo, CreateRepoInput } from '../types/repo'
import { RepoStatusSchema } from '@opencode-manager/shared/schemas'
import { getReposPath } from '@opencode-manager/shared/config/env'
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, getRepoDisplayName } from '@opencode-manager/shared/utils'
import { getErrorMessage } from '../utils/error-utils'
import { canonicalPathSync } from '../utils/fs-safe'
import { invalidateRepoEnvCache } from '../utils/repo-env-cache'
import { z } from 'zod'
import path from 'path'
import { selectRow, selectRows } from './rows'
const RepoRowSchema = z.object({
id: z.number(),
name: z.string().nullish(),
repo_url: z.string().nullish(),
local_path: z.string(),
source_path: z.string().nullish(),
branch: z.string().nullish(),
default_branch: z.string(),
clone_status: RepoStatusSchema,
cloned_at: z.number(),
last_pulled: z.number().nullish(),
last_accessed_at: z.number().nullish(),
is_worktree: z.number().nullish(),
is_local: z.number().nullish(),
})
type RepoRow = z.infer<typeof RepoRowSchema>
const RepoIdRowSchema = z.object({ id: z.number() })
const RepoSettingRowSchema = z.object({ value: z.string() })
const REPO_GIT_CREDENTIAL_SETTING_KEY = 'gitCredentialId'
const REPO_SANDBOX_GIT_CREDENTIALS_SETTING_KEY = 'sandboxGitCredentials'
function rowToRepo(row: RepoRow): Repo {
const fullPath = row.source_path || path.join(getReposPath(), row.local_path)
return {
id: row.id,
name: row.name ?? undefined,
repoUrl: row.repo_url ?? undefined,
localPath: row.local_path,
fullPath,
sourcePath: row.source_path ?? undefined,
branch: row.branch ?? undefined,
defaultBranch: row.default_branch,
cloneStatus: row.clone_status,
clonedAt: row.cloned_at,
lastPulled: row.last_pulled ?? undefined,
lastAccessedAt: row.last_accessed_at ?? undefined,
isWorktree: row.is_worktree ? Boolean(row.is_worktree) : undefined,
isLocal: row.is_local ? Boolean(row.is_local) : undefined,
}
}
export function getRepoSetting(db: Database, repoId: number, key: string): string | null {
const row = selectRow(db, RepoSettingRowSchema, 'SELECT value FROM repo_settings WHERE repo_id = ? AND key = ?', repoId, key)
return row?.value ?? null
}
export function setRepoSetting(db: Database, repoId: number, key: string, value: string | null): void {
const now = Date.now()
const updateSetting = db.transaction(() => {
if (value === null || value === '') {
db.prepare('DELETE FROM repo_settings WHERE repo_id = ? AND key = ?').run(repoId, key)
return
}
db.prepare(`
INSERT INTO repo_settings (repo_id, key, value, updated_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(repo_id, key) DO UPDATE SET
value = excluded.value,
updated_at = excluded.updated_at
`).run(repoId, key, value, now)
})
updateSetting()
}
export function getRepoGitCredentialId(db: Database, repoId: number): string | null {
return getRepoSetting(db, repoId, REPO_GIT_CREDENTIAL_SETTING_KEY)
}
export function setRepoGitCredentialId(db: Database, repoId: number, credentialId: string | null): void {
setRepoSetting(db, repoId, REPO_GIT_CREDENTIAL_SETTING_KEY, credentialId)
}
export function getRepoSandboxGitCredentials(db: Database, repoId: number): boolean | null {
const value = getRepoSetting(db, repoId, REPO_SANDBOX_GIT_CREDENTIALS_SETTING_KEY)
if (value === null) return null
return value === 'true'
}
export function setRepoSandboxGitCredentials(db: Database, repoId: number, allowed: boolean | null): void {
setRepoSetting(db, repoId, REPO_SANDBOX_GIT_CREDENTIALS_SETTING_KEY, allowed === null ? null : String(allowed))
}
export function getRepoByExactDirectory(db: Database, directory: string): Repo | null {
const resolvedDirectory = canonicalPathSync(path.resolve(directory))
return listRepos(db).find((repo) => canonicalPathSync(path.resolve(repo.fullPath)) === resolvedDirectory) ?? null
}
export function getRepoByDirectory(db: Database, directory: string): Repo | null {
const resolvedDirectory = canonicalPathSync(path.resolve(directory))
const repos = listRepos(db)
return repos
.filter((repo) => {
const resolvedRepoPath = canonicalPathSync(path.resolve(repo.fullPath))
const relativePath = path.relative(resolvedRepoPath, resolvedDirectory)
return relativePath === '' || (!!relativePath && !relativePath.startsWith('..') && !path.isAbsolute(relativePath))
})
.sort((a, b) => b.fullPath.length - a.fullPath.length)[0] ?? null
}
const TABLES_WITH_REPO_ID = ['schedule_jobs', 'schedule_runs', 'repo_settings'] as const
type RepoIdTable = typeof TABLES_WITH_REPO_ID[number]
function updateRepoIdReference(db: Database, tableName: RepoIdTable, fromRepoId: number, toRepoId: number): void {
db.prepare(`UPDATE ${tableName} SET repo_id = ? WHERE repo_id = ?`).run(toRepoId, fromRepoId)
}
export function getRepoById(db: Database, id: number): Repo | null {
const row = selectRow(db, RepoRowSchema, 'SELECT * FROM repos WHERE id = ?', id)
return row ? rowToRepo(row) : null
}
export function ensureAssistantRepo(db: Database): Repo {
const now = Date.now()
const syncAssistantRepo = db.transaction(() => {
const existingAssistantPathRow = selectRow(
db,
RepoIdRowSchema,
'SELECT id FROM repos WHERE local_path = ? AND id != ?',
ASSISTANT_REPO_PATH,
ASSISTANT_REPO_ID,
)
if (existingAssistantPathRow) {
for (const table of TABLES_WITH_REPO_ID) {
updateRepoIdReference(db, table, existingAssistantPathRow.id, ASSISTANT_REPO_ID)
}
db.prepare('DELETE FROM repos WHERE id = ?').run(existingAssistantPathRow.id)
}
db.prepare(`
INSERT INTO repos (
id,
repo_url,
local_path,
source_path,
branch,
default_branch,
clone_status,
cloned_at,
last_accessed_at,
is_worktree,
is_local
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
repo_url = excluded.repo_url,
local_path = excluded.local_path,
source_path = excluded.source_path,
branch = excluded.branch,
default_branch = excluded.default_branch,
clone_status = excluded.clone_status,
last_accessed_at = excluded.last_accessed_at,
is_worktree = excluded.is_worktree,
is_local = excluded.is_local
`).run(
ASSISTANT_REPO_ID,
null,
ASSISTANT_REPO_PATH,
null,
null,
'main',
'ready',
now,
now,
0,
0,
)
})
syncAssistantRepo()
const repo = getRepoById(db, ASSISTANT_REPO_ID)
if (!repo) {
throw new Error('Failed to sync Assistant repository')
}
return repo
}
export function createRepo(db: Database, repo: CreateRepoInput): Repo {
invalidateRepoEnvCache()
const normalizedPath = repo.localPath.trim().replace(/\/+$/, '')
const existing = repo.isLocal
? repo.sourcePath
? getRepoBySourcePath(db, repo.sourcePath) ?? getRepoByLocalPath(db, normalizedPath)
: getRepoByLocalPath(db, normalizedPath)
: getRepoByUrlAndBranch(db, repo.repoUrl, repo.branch)
if (existing) {
return existing
}
const stmt = db.prepare(`
INSERT INTO repos (repo_url, local_path, source_path, branch, default_branch, clone_status, cloned_at, last_accessed_at, is_worktree, is_local)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`)
try {
const result = stmt.run(
repo.repoUrl || null,
normalizedPath,
repo.sourcePath || null,
repo.branch || null,
repo.defaultBranch,
repo.cloneStatus,
repo.clonedAt,
repo.clonedAt,
repo.isWorktree ? 1 : 0,
repo.isLocal ? 1 : 0
)
const newRepo = getRepoById(db, Number(result.lastInsertRowid))
if (!newRepo) {
throw new Error(`Failed to retrieve newly created repo with id ${result.lastInsertRowid}`)
}
return newRepo
} catch (error) {
const errorMessage = getErrorMessage(error)
const isUniqueConstraintCode = error instanceof Error && 'code' in error && error.code === 'SQLITE_CONSTRAINT_UNIQUE'
if (errorMessage.includes('UNIQUE constraint failed') || isUniqueConstraintCode) {
const conflictRepo = repo.isLocal
? repo.sourcePath
? getRepoBySourcePath(db, repo.sourcePath) ?? getRepoByLocalPath(db, normalizedPath)
: getRepoByLocalPath(db, normalizedPath)
: getRepoByUrlAndBranch(db, repo.repoUrl, repo.branch)
if (conflictRepo) {
return conflictRepo
}
const identifier = repo.isLocal ? `path '${normalizedPath}'` : `url '${repo.repoUrl}' branch '${repo.branch || 'default'}'`
throw new Error(`Repository with ${identifier} already exists but could not be retrieved. This may indicate database corruption.`)
}
throw new Error(`Failed to create repository: ${errorMessage}`)
}
}
export function getRepoByUrlAndBranch(db: Database, repoUrl: string, branch?: string): Repo | null {
const row = branch
? selectRow(db, RepoRowSchema, 'SELECT * FROM repos WHERE repo_url = ? AND branch = ?', repoUrl, branch)
: selectRow(db, RepoRowSchema, 'SELECT * FROM repos WHERE repo_url = ? AND branch IS NULL', repoUrl)
return row ? rowToRepo(row) : null
}
export function getRepoByLocalPath(db: Database, localPath: string): Repo | null {
const row = selectRow(db, RepoRowSchema, 'SELECT * FROM repos WHERE local_path = ?', localPath)
return row ? rowToRepo(row) : null
}
export function getRepoBySourcePath(db: Database, sourcePath: string): Repo | null {
const row = selectRow(db, RepoRowSchema, 'SELECT * FROM repos WHERE source_path = ?', sourcePath)
return row ? rowToRepo(row) : null
}
export function listRepos(db: Database, repoOrder?: number[]): Repo[] {
const rows = selectRows(db, RepoRowSchema, 'SELECT * FROM repos ORDER BY cloned_at DESC')
const repos = rows.map(rowToRepo)
if (!repoOrder || repoOrder.length === 0) {
return repos
}
const orderMap = new Map(repoOrder.map((id, index) => [id, index]))
const orderedRepos = repos
.filter((repo) => orderMap.has(repo.id))
.sort((a, b) => {
const indexA = orderMap.get(a.id)!
const indexB = orderMap.get(b.id)!
return indexA - indexB
})
const remainingRepos = repos
.filter((repo) => !orderMap.has(repo.id))
.sort((a, b) => {
const nameA = getRepoName(a).toLowerCase()
const nameB = getRepoName(b).toLowerCase()
return nameA.localeCompare(nameB)
})
return [...orderedRepos, ...remainingRepos]
}
export function getRepoName(repo: Repo): string {
return getRepoDisplayName(repo)
}
export function updateRepoStatus(db: Database, id: number, cloneStatus: Repo['cloneStatus']): void {
const stmt = db.prepare('UPDATE repos SET clone_status = ? WHERE id = ?')
const result = stmt.run(cloneStatus, id)
if (result.changes === 0) {
throw new Error(`Repository with id ${id} not found`)
}
}
export function updateLastPulled(db: Database, id: number): void {
const stmt = db.prepare('UPDATE repos SET last_pulled = ? WHERE id = ?')
const result = stmt.run(Date.now(), id)
if (result.changes === 0) {
throw new Error(`Repository with id ${id} not found`)
}
}
export function updateLastAccessed(db: Database, id: number): void {
const stmt = db.prepare('UPDATE repos SET last_accessed_at = ? WHERE id = ?')
const result = stmt.run(Date.now(), id)
if (result.changes === 0) {
throw new Error(`Repository with id ${id} not found`)
}
}
export function updateRepoBranch(db: Database, id: number, branch: string): void {
const stmt = db.prepare('UPDATE repos SET branch = ? WHERE id = ?')
const result = stmt.run(branch, id)
if (result.changes === 0) {
throw new Error(`Repository with id ${id} not found`)
}
}
export function updateRepoName(db: Database, id: number, name: string | null): void {
const stmt = db.prepare('UPDATE repos SET name = ? WHERE id = ?')
const result = stmt.run(name, id)
if (result.changes === 0) {
throw new Error(`Repository with id ${id} not found`)
}
}
export function deleteRepo(db: Database, id: number): void {
if (id === ASSISTANT_REPO_ID) {
return
}
const remove = db.transaction(() => {
db.prepare('DELETE FROM multi_run_fusions WHERE multi_run_id IN (SELECT id FROM multi_runs WHERE repo_id = ?)').run(id)
db.prepare('DELETE FROM multi_run_entries WHERE multi_run_id IN (SELECT id FROM multi_runs WHERE repo_id = ?)').run(id)
db.prepare('DELETE FROM multi_runs WHERE repo_id = ?').run(id)
db.prepare('DELETE FROM secrets WHERE repo_id = ?').run(id)
for (const table of TABLES_WITH_REPO_ID) {
db.prepare(`DELETE FROM ${table} WHERE repo_id = ?`).run(id)
}
db.prepare('DELETE FROM repos WHERE id = ?').run(id)
})
remove()
invalidateRepoEnvCache()
}