diff --git a/apps/backend/internal/automation/run_retention.go b/apps/backend/internal/automation/run_retention.go index 423b870cb7..913dd6254c 100644 --- a/apps/backend/internal/automation/run_retention.go +++ b/apps/backend/internal/automation/run_retention.go @@ -114,7 +114,7 @@ func (s *Store) PrunableRunTaskIDs(ctx context.Context, finalizedTaskID string, // retention unit is the distinct task checkout, not each run row. Keep the // newest run ordering for each task, and protect the current continuation // even when it has already parked after a successful turn. - err := s.ro.SelectContext(ctx, &taskIDs, ` + err := s.ro.SelectContext(ctx, &taskIDs, s.ro.Rebind(` WITH terminal_tasks AS ( SELECT ar.automation_id, ar.task_id, MAX(ar.created_at) AS latest_created_at, @@ -139,7 +139,7 @@ func (s *Store) PrunableRunTaskIDs(ctx context.Context, finalizedTaskID string, ) AND`+strings.ReplaceAll(runHasLiveWorktreeSQL, "ar.task_id", "tt.task_id")+` ORDER BY tt.latest_created_at DESC, tt.latest_id DESC - LIMIT ? OFFSET ?`, args...) + LIMIT ? OFFSET ?`), args...) return taskIDs, err } @@ -167,11 +167,11 @@ func (s *Store) RunWorkspaceInUse(ctx context.Context, taskID string) (bool, err } var inUse bool args := append([]any{taskID}, runWorktreeInUseArgs()...) - err := s.ro.GetContext(ctx, &inUse, ` + err := s.ro.GetContext(ctx, &inUse, s.ro.Rebind(` SELECT EXISTS ( SELECT 1 FROM task_sessions ts WHERE ts.task_id = ? AND ts.state IN (?, ?) - )`, args...) + )`), args...) return inUse, err } diff --git a/apps/backend/internal/automation/store.go b/apps/backend/internal/automation/store.go index 7f7a7410b1..397971632f 100644 --- a/apps/backend/internal/automation/store.go +++ b/apps/backend/internal/automation/store.go @@ -15,6 +15,7 @@ import ( "github.com/jmoiron/sqlx" "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/db/dialect" taskmodels "github.com/kandev/kandev/internal/task/models" ) @@ -187,22 +188,22 @@ const automationColumns = `id, workspace_id, name, description, workflow_id, wor execution_mode = 'task' AS legacy_board_card` func (s *Store) initSchema() error { - if _, err := s.db.Exec(createTablesSQL); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(createTablesSQL, s.db.DriverName())); err != nil { return err } - s.db.Exec(migrateTaskTitleSQL) //nolint:errcheck // duplicate-column on existing DBs - s.db.Exec(migrateExecutionModeSQL) //nolint:errcheck // duplicate-column on existing DBs - s.db.Exec(migrateRepositoryIDSQL) //nolint:errcheck // duplicate-column on existing DBs - s.db.Exec(migrateContinuationPolicySQL) //nolint:errcheck // duplicate-column on existing DBs - s.db.Exec(migrateContinuationTaskSQL) //nolint:errcheck // duplicate-column on existing DBs - s.db.Exec(migrateTaskModeSQL) //nolint:errcheck // duplicate-column on existing DBs - s.db.Exec(migrateRepositoryModeSQL) //nolint:errcheck // duplicate-column on existing DBs - s.db.Exec(migrateRepositoryBranchSQL) //nolint:errcheck // duplicate-column on existing DBs - s.db.Exec(migrateRunSessionSQL) //nolint:errcheck // duplicate-column on existing DBs - s.db.Exec(migrateRunTurnSQL) //nolint:errcheck // duplicate-column on existing DBs - s.db.Exec(migrateRunThreadActionSQL) //nolint:errcheck // duplicate-column on existing DBs - s.db.Exec(migrateRunThreadReasonSQL) //nolint:errcheck // duplicate-column on existing DBs - s.db.Exec(migrateRunDisplayTitleSQL) //nolint:errcheck // duplicate-column on existing DBs + s.db.Exec(schemaSQLForDriver(migrateTaskTitleSQL, s.db.DriverName())) //nolint:errcheck // duplicate-column on existing DBs + s.db.Exec(schemaSQLForDriver(migrateExecutionModeSQL, s.db.DriverName())) //nolint:errcheck // duplicate-column on existing DBs + s.db.Exec(schemaSQLForDriver(migrateRepositoryIDSQL, s.db.DriverName())) //nolint:errcheck // duplicate-column on existing DBs + s.db.Exec(schemaSQLForDriver(migrateContinuationPolicySQL, s.db.DriverName())) //nolint:errcheck // duplicate-column on existing DBs + s.db.Exec(schemaSQLForDriver(migrateContinuationTaskSQL, s.db.DriverName())) //nolint:errcheck // duplicate-column on existing DBs + s.db.Exec(schemaSQLForDriver(migrateTaskModeSQL, s.db.DriverName())) //nolint:errcheck // duplicate-column on existing DBs + s.db.Exec(schemaSQLForDriver(migrateRepositoryModeSQL, s.db.DriverName())) //nolint:errcheck // duplicate-column on existing DBs + s.db.Exec(schemaSQLForDriver(migrateRepositoryBranchSQL, s.db.DriverName())) //nolint:errcheck // duplicate-column on existing DBs + s.db.Exec(schemaSQLForDriver(migrateRunSessionSQL, s.db.DriverName())) //nolint:errcheck // duplicate-column on existing DBs + s.db.Exec(schemaSQLForDriver(migrateRunTurnSQL, s.db.DriverName())) //nolint:errcheck // duplicate-column on existing DBs + s.db.Exec(schemaSQLForDriver(migrateRunThreadActionSQL, s.db.DriverName())) //nolint:errcheck // duplicate-column on existing DBs + s.db.Exec(schemaSQLForDriver(migrateRunThreadReasonSQL, s.db.DriverName())) //nolint:errcheck // duplicate-column on existing DBs + s.db.Exec(schemaSQLForDriver(migrateRunDisplayTitleSQL, s.db.DriverName())) //nolint:errcheck // duplicate-column on existing DBs if err := s.backfillLegacyRepositoryIDs(); err != nil { return err } @@ -221,8 +222,8 @@ func (s *Store) backfillLegacyRepositoryIDs() error { CreatedAt time.Time `db:"created_at"` } var rows []legacyRow - err := s.db.Select(&rows, - `SELECT id, repository_id, created_at FROM automations WHERE repository_id != ''`) + err := s.db.Select(&rows, s.db.Rebind( + `SELECT id, repository_id, created_at FROM automations WHERE repository_id != ''`)) if err != nil { return fmt.Errorf("select legacy repository_id rows: %w", err) } @@ -236,9 +237,10 @@ func (s *Store) backfillLegacyRepositoryIDs() error { defer func() { _ = tx.Rollback() }() for _, row := range rows { - _, err := tx.Exec( - `INSERT OR IGNORE INTO automation_repositories (id, automation_id, repository_id, position, created_at) - VALUES (?, ?, ?, 0, ?)`, + _, err := tx.Exec(tx.Rebind( + `INSERT INTO automation_repositories (id, automation_id, repository_id, position, created_at) + VALUES (?, ?, ?, 0, ?) + ON CONFLICT(automation_id, repository_id) DO NOTHING`), uuid.New().String(), row.ID, row.RepositoryID, row.CreatedAt) if err != nil { return fmt.Errorf("backfill automation_repositories for %s: %w", row.ID, err) @@ -248,7 +250,7 @@ func (s *Store) backfillLegacyRepositoryIDs() error { // repository from automation_repositories would resurrect it on // the next boot's backfill pass (INSERT OR IGNORE only blocks // exact re-insertion, not re-addition after deletion). - if _, err := tx.Exec(`UPDATE automations SET repository_id = '' WHERE id = ?`, row.ID); err != nil { + if _, err := tx.Exec(tx.Rebind(`UPDATE automations SET repository_id = '' WHERE id = ?`), row.ID); err != nil { return fmt.Errorf("clear legacy repository_id for %s: %w", row.ID, err) } } @@ -320,13 +322,13 @@ func (s *Store) CreateAutomation(ctx context.Context, a *Automation) error { // indistinguishable from a pre-upgrade one, and the one-time notice would // never stop being true. Empty means "no mode was ever chosen", which is // the honest record for a row created after the choice was withdrawn. - _, err = tx.ExecContext(ctx, ` + _, err = tx.ExecContext(ctx, tx.Rebind(` INSERT INTO automations (id, workspace_id, name, description, workflow_id, workflow_step_id, agent_profile_id, executor_profile_id, task_mode, repository_mode, prompt, task_title_template, execution_mode, enabled, max_concurrent_runs, continuation_policy, continuation_task_id, webhook_secret, last_triggered_at, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?)`), a.ID, a.WorkspaceID, a.Name, a.Description, a.WorkflowID, a.WorkflowStepID, a.AgentProfileID, a.ExecutorProfileID, string(a.TaskMode), string(a.RepositoryMode), @@ -348,9 +350,9 @@ func (s *Store) CreateAutomation(ctx context.Context, a *Automation) error { func insertAutomationRepositories(ctx context.Context, tx *sqlx.Tx, automationID string, repositories []AutomationRepository) error { now := time.Now().UTC() for i, repository := range repositories { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO automation_repositories (id, automation_id, repository_id, base_branch, position, created_at) - VALUES (?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?)`), uuid.New().String(), automationID, repository.RepositoryID, repository.BaseBranch, i, now) if err != nil { return fmt.Errorf("insert automation_repositories: %w", err) @@ -363,7 +365,7 @@ func insertAutomationRepositories(ctx context.Context, tx *sqlx.Tx, automationID // repository_ids hydrated. func (s *Store) GetAutomation(ctx context.Context, id string) (*Automation, error) { var a Automation - err := s.ro.GetContext(ctx, &a, `SELECT `+automationColumns+` FROM automations WHERE id = ?`, id) + err := s.ro.GetContext(ctx, &a, s.ro.Rebind(`SELECT `+automationColumns+` FROM automations WHERE id = ?`), id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -439,7 +441,7 @@ func (s *Store) ListEnabledByAgentProfile(ctx context.Context, agentProfileID st var rows []AgentProfileBinding err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind(` SELECT id, name, workspace_id FROM automations - WHERE agent_profile_id = ? AND enabled = 1 + WHERE agent_profile_id = ? AND enabled = TRUE ORDER BY name `), agentProfileID) if err != nil { @@ -467,8 +469,8 @@ func (s *Store) DisableByAgentProfile(ctx context.Context, agentProfileID string return nil, nil } _, err = s.db.ExecContext(ctx, s.db.Rebind(` - UPDATE automations SET enabled = 0, updated_at = ? - WHERE agent_profile_id = ? AND enabled = 1 + UPDATE automations SET enabled = FALSE, updated_at = ? + WHERE agent_profile_id = ? AND enabled = TRUE `), time.Now().UTC(), agentProfileID) if err != nil { return nil, fmt.Errorf("disable automations for agent profile: %w", err) @@ -480,8 +482,8 @@ func (s *Store) DisableByAgentProfile(ctx context.Context, agentProfileID string // repository_ids hydrated. func (s *Store) ListAutomations(ctx context.Context, workspaceID string) ([]*Automation, error) { var automations []*Automation - err := s.ro.SelectContext(ctx, &automations, - `SELECT `+automationColumns+` FROM automations WHERE workspace_id = ? ORDER BY created_at DESC`, workspaceID) + err := s.ro.SelectContext(ctx, &automations, s.ro.Rebind( + `SELECT `+automationColumns+` FROM automations WHERE workspace_id = ? ORDER BY created_at DESC`), workspaceID) if err != nil { return nil, err } @@ -491,8 +493,8 @@ func (s *Store) ListAutomations(ctx context.Context, workspaceID string) ([]*Aut // ListAllEnabled returns all enabled automations (across workspaces). func (s *Store) ListAllEnabled(ctx context.Context) ([]*Automation, error) { var automations []*Automation - err := s.ro.SelectContext(ctx, &automations, - `SELECT `+automationColumns+` FROM automations WHERE enabled = 1 ORDER BY created_at`) + err := s.ro.SelectContext(ctx, &automations, s.ro.Rebind( + `SELECT `+automationColumns+` FROM automations WHERE enabled = TRUE ORDER BY created_at`)) if err != nil { return nil, err } @@ -569,12 +571,12 @@ func (s *Store) UpdateAutomation(ctx context.Context, id string, req *UpdateAuto } defer func() { _ = tx.Rollback() }() - _, err = tx.ExecContext(ctx, ` + _, err = tx.ExecContext(ctx, tx.Rebind(` UPDATE automations SET name = ?, description = ?, workflow_id = ?, workflow_step_id = ?, agent_profile_id = ?, executor_profile_id = ?, task_mode = ?, repository_mode = ?, prompt = ?, task_title_template = ?, enabled = ?, max_concurrent_runs = ?, continuation_policy = ?, updated_at = ? - WHERE id = ?`, + WHERE id = ?`), a.Name, a.Description, a.WorkflowID, a.WorkflowStepID, a.AgentProfileID, a.ExecutorProfileID, string(a.TaskMode), string(a.RepositoryMode), @@ -584,14 +586,14 @@ func (s *Store) UpdateAutomation(ctx context.Context, id string, req *UpdateAuto return err } if req.Repositories != nil || req.RepositoryIDs != nil { - if _, err := tx.ExecContext(ctx, `DELETE FROM automation_repositories WHERE automation_id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(`DELETE FROM automation_repositories WHERE automation_id = ?`), id); err != nil { return fmt.Errorf("clear automation_repositories: %w", err) } if err := insertAutomationRepositories(ctx, tx, id, a.Repositories); err != nil { return err } } else if req.RepositoryMode != nil && *req.RepositoryMode != RepositoryModeSelected { - if _, err := tx.ExecContext(ctx, `DELETE FROM automation_repositories WHERE automation_id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(`DELETE FROM automation_repositories WHERE automation_id = ?`), id); err != nil { return fmt.Errorf("clear automation_repositories for repository mode: %w", err) } } @@ -691,7 +693,7 @@ func repositoryIDs(repositories []AutomationRepository) []string { // DeleteAutomation removes an automation and its triggers/runs (CASCADE). func (s *Store) DeleteAutomation(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM automations WHERE id = ?`, id) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM automations WHERE id = ?`), id) return err } @@ -713,10 +715,10 @@ type AutomationTaskCleanupJob struct { // limit was applied. func (s *Store) ListOpenRuns(ctx context.Context, automationID string) ([]*AutomationRun, error) { var runs []*AutomationRun - err := s.ro.SelectContext(ctx, &runs, ` + err := s.ro.SelectContext(ctx, &runs, s.ro.Rebind(` SELECT * FROM automation_runs WHERE automation_id = ? AND status IN (?, ?) - ORDER BY created_at ASC, id ASC`, + ORDER BY created_at ASC, id ASC`), automationID, string(RunStatusTriggered), string(RunStatusTaskCreated)) for _, run := range runs { run.TriggerData = json.RawMessage(run.TriggerDataJSON) @@ -729,10 +731,10 @@ func (s *Store) ListOpenRuns(ctx context.Context, automationID string) ([]*Autom // disappear from recovery. func (s *Store) ListAllOpenRuns(ctx context.Context) ([]*AutomationRun, error) { var runs []*AutomationRun - err := s.ro.SelectContext(ctx, &runs, ` + err := s.ro.SelectContext(ctx, &runs, s.ro.Rebind(` SELECT * FROM automation_runs WHERE status IN (?, ?) - ORDER BY automation_id, created_at ASC, id ASC`, + ORDER BY automation_id, created_at ASC, id ASC`), string(RunStatusTriggered), string(RunStatusTaskCreated)) for _, run := range runs { run.TriggerData = json.RawMessage(run.TriggerDataJSON) @@ -776,7 +778,7 @@ func (s *Store) DeleteAutomationWithCleanup(ctx context.Context, id string, clea if err != nil { return nil, err } - if _, err := tx.ExecContext(ctx, `DELETE FROM automations WHERE id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(`DELETE FROM automations WHERE id = ?`), id); err != nil { return nil, err } if err := tx.Commit(); err != nil { @@ -790,13 +792,13 @@ func (s *Store) DeleteAutomationWithCleanup(ctx context.Context, id string, clea // origin to keep visible normal tasks out of hidden-task cleanup jobs. func (s *Store) ListAutomationTaskIDs(ctx context.Context, id string) ([]string, error) { var taskIDs []string - if err := s.ro.SelectContext(ctx, &taskIDs, - `SELECT DISTINCT task_id FROM automation_runs WHERE automation_id = ? AND task_id != ''`, id); err != nil { + if err := s.ro.SelectContext(ctx, &taskIDs, s.ro.Rebind( + `SELECT DISTINCT task_id FROM automation_runs WHERE automation_id = ? AND task_id != ''`), id); err != nil { return nil, err } var continuationTaskID string - if err := s.ro.GetContext(ctx, &continuationTaskID, - `SELECT continuation_task_id FROM automations WHERE id = ?`, id); err == nil && continuationTaskID != "" { + if err := s.ro.GetContext(ctx, &continuationTaskID, s.ro.Rebind( + `SELECT continuation_task_id FROM automations WHERE id = ?`), id); err == nil && continuationTaskID != "" { taskIDs = append(taskIDs, continuationTaskID) } else if err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, err @@ -806,8 +808,8 @@ func (s *Store) ListAutomationTaskIDs(ctx context.Context, id string) ([]string, func loadAutomationCleanupOwner(ctx context.Context, tx *sqlx.Tx, id string) (automationCleanupOwner, bool, error) { var owner automationCleanupOwner - err := tx.GetContext(ctx, &owner, - `SELECT workspace_id, continuation_task_id FROM automations WHERE id = ?`, id) + err := tx.GetContext(ctx, &owner, tx.Rebind( + `SELECT workspace_id, continuation_task_id FROM automations WHERE id = ?`), id) if errors.Is(err, sql.ErrNoRows) { return owner, false, nil } @@ -816,8 +818,8 @@ func loadAutomationCleanupOwner(ctx context.Context, tx *sqlx.Tx, id string) (au func listAutomationCleanupTaskIDs(ctx context.Context, tx *sqlx.Tx, id, continuationTaskID string) ([]string, error) { var taskIDs []string - if err := tx.SelectContext(ctx, &taskIDs, - `SELECT DISTINCT task_id FROM automation_runs WHERE automation_id = ? AND task_id != ''`, id); err != nil { + if err := tx.SelectContext(ctx, &taskIDs, tx.Rebind( + `SELECT DISTINCT task_id FROM automation_runs WHERE automation_id = ? AND task_id != ''`), id); err != nil { return nil, err } if continuationTaskID != "" { @@ -851,14 +853,14 @@ func insertAutomationCleanupJobs( if !owned { continue } - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO automation_task_cleanup_jobs (task_id, workspace_id, automation_id, last_error, created_at, updated_at) VALUES (?, ?, ?, '', ?, ?) ON CONFLICT(task_id) DO UPDATE SET workspace_id = excluded.workspace_id, automation_id = excluded.automation_id, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), taskID, owner.WorkspaceID, automationID, now, now); err != nil { return nil, err } @@ -869,18 +871,18 @@ func insertAutomationCleanupJobs( func automationCleanupTaskIsUnreferenced(ctx context.Context, tx *sqlx.Tx, automationID, taskID string) (bool, error) { var refs int - if err := tx.GetContext(ctx, &refs, ` + if err := tx.GetContext(ctx, &refs, tx.Rebind(` SELECT COUNT(*) FROM automation_runs - WHERE task_id = ? AND automation_id != ?`, taskID, automationID); err != nil { + WHERE task_id = ? AND automation_id != ?`), taskID, automationID); err != nil { return false, err } if refs > 0 { return false, nil } var pointers int - if err := tx.GetContext(ctx, &pointers, ` + if err := tx.GetContext(ctx, &pointers, tx.Rebind(` SELECT COUNT(*) FROM automations - WHERE continuation_task_id = ? AND id != ?`, taskID, automationID); err != nil { + WHERE continuation_task_id = ? AND id != ?`), taskID, automationID); err != nil { return false, err } return pointers == 0, nil @@ -895,9 +897,9 @@ func (s *Store) IsTaskReferencedByOtherAutomation(ctx context.Context, automatio return false, nil } var refs int - err := s.ro.GetContext(ctx, &refs, ` + err := s.ro.GetContext(ctx, &refs, s.ro.Rebind(` SELECT COUNT(*) FROM automation_runs - WHERE task_id = ? AND automation_id != ?`, taskID, automationID) + WHERE task_id = ? AND automation_id != ?`), taskID, automationID) if err != nil { return false, err } @@ -905,9 +907,9 @@ func (s *Store) IsTaskReferencedByOtherAutomation(ctx context.Context, automatio return true, nil } var pointers int - err = s.ro.GetContext(ctx, &pointers, ` + err = s.ro.GetContext(ctx, &pointers, s.ro.Rebind(` SELECT COUNT(*) FROM automations - WHERE continuation_task_id = ? AND id != ?`, taskID, automationID) + WHERE continuation_task_id = ? AND id != ?`), taskID, automationID) return pointers > 0, err } @@ -918,9 +920,9 @@ func (s *Store) IsTaskReferencedByRun(ctx context.Context, automationID, runID, return false, nil } var count int - err := s.ro.GetContext(ctx, &count, ` + err := s.ro.GetContext(ctx, &count, s.ro.Rebind(` SELECT COUNT(*) FROM automation_runs - WHERE automation_id = ? AND id != ? AND task_id = ?`, automationID, runID, taskID) + WHERE automation_id = ? AND id != ? AND task_id = ?`), automationID, runID, taskID) return count > 0, err } @@ -928,34 +930,34 @@ func (s *Store) IsTaskReferencedByRun(ctx context.Context, automationID, runID, // task from run-row deletion. func (s *Store) IsContinuationTask(ctx context.Context, automationID, taskID string) (bool, error) { var count int - err := s.ro.GetContext(ctx, &count, - `SELECT COUNT(*) FROM automations WHERE id = ? AND continuation_task_id = ?`, automationID, taskID) + err := s.ro.GetContext(ctx, &count, s.ro.Rebind( + `SELECT COUNT(*) FROM automations WHERE id = ? AND continuation_task_id = ?`), automationID, taskID) return count > 0, err } func (s *Store) ListCleanupJobs(ctx context.Context) ([]*AutomationTaskCleanupJob, error) { var jobs []*AutomationTaskCleanupJob - err := s.ro.SelectContext(ctx, &jobs, - `SELECT * FROM automation_task_cleanup_jobs ORDER BY created_at ASC, task_id ASC`) + err := s.ro.SelectContext(ctx, &jobs, s.ro.Rebind( + `SELECT * FROM automation_task_cleanup_jobs ORDER BY created_at ASC, task_id ASC`)) return jobs, err } func (s *Store) DeleteCleanupJob(ctx context.Context, taskID string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM automation_task_cleanup_jobs WHERE task_id = ?`, taskID) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM automation_task_cleanup_jobs WHERE task_id = ?`), taskID) return err } func (s *Store) UpdateCleanupJobError(ctx context.Context, taskID, message string) error { - _, err := s.db.ExecContext(ctx, ` - UPDATE automation_task_cleanup_jobs SET last_error = ?, updated_at = ? WHERE task_id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind(` + UPDATE automation_task_cleanup_jobs SET last_error = ?, updated_at = ? WHERE task_id = ?`), message, time.Now().UTC(), taskID) return err } // UpdateLastTriggered updates the last_triggered_at timestamp. func (s *Store) UpdateLastTriggered(ctx context.Context, id string, t time.Time) error { - _, err := s.db.ExecContext(ctx, - `UPDATE automations SET last_triggered_at = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE automations SET last_triggered_at = ?, updated_at = ? WHERE id = ?`), t, time.Now().UTC(), id) return err } @@ -971,9 +973,9 @@ func (s *Store) CreateTrigger(ctx context.Context, t *AutomationTrigger) error { t.CreatedAt = now t.UpdatedAt = now t.ConfigJSON = string(t.Config) - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO automation_triggers (id, automation_id, type, config, enabled, last_evaluated_at, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`), t.ID, t.AutomationID, t.Type, t.ConfigJSON, t.Enabled, t.LastEvaluatedAt, t.CreatedAt, t.UpdatedAt) return err } @@ -982,16 +984,16 @@ func (s *Store) CreateTrigger(ctx context.Context, t *AutomationTrigger) error { // the auth layer to authorize trigger mutations by workspace ownership. func (s *Store) GetTriggerAutomationID(ctx context.Context, triggerID string) (string, error) { var automationID string - err := s.ro.GetContext(ctx, &automationID, - `SELECT automation_id FROM automation_triggers WHERE id = ?`, triggerID) + err := s.ro.GetContext(ctx, &automationID, s.ro.Rebind( + `SELECT automation_id FROM automation_triggers WHERE id = ?`), triggerID) return automationID, err } // GetTrigger returns a single trigger, or nil when it no longer exists. func (s *Store) GetTrigger(ctx context.Context, id string) (*AutomationTrigger, error) { var triggers []AutomationTrigger - if err := s.ro.SelectContext(ctx, &triggers, - `SELECT * FROM automation_triggers WHERE id = ?`, id); err != nil { + if err := s.ro.SelectContext(ctx, &triggers, s.ro.Rebind( + `SELECT * FROM automation_triggers WHERE id = ?`), id); err != nil { return nil, err } if len(triggers) == 0 { @@ -1004,8 +1006,8 @@ func (s *Store) GetTrigger(ctx context.Context, id string) (*AutomationTrigger, // ListTriggers returns all triggers for an automation. func (s *Store) ListTriggers(ctx context.Context, automationID string) ([]AutomationTrigger, error) { var triggers []AutomationTrigger - err := s.ro.SelectContext(ctx, &triggers, - `SELECT * FROM automation_triggers WHERE automation_id = ? ORDER BY created_at`, automationID) + err := s.ro.SelectContext(ctx, &triggers, s.ro.Rebind( + `SELECT * FROM automation_triggers WHERE automation_id = ? ORDER BY created_at`), automationID) hydrateTriggers(triggers) return triggers, err } @@ -1042,7 +1044,7 @@ func (s *Store) listTriggersForAutomations(ctx context.Context, automationIDs [] // UpdateTrigger applies partial updates to a trigger. func (s *Store) UpdateTrigger(ctx context.Context, id string, req *UpdateTriggerRequest) error { var t AutomationTrigger - err := s.ro.GetContext(ctx, &t, `SELECT * FROM automation_triggers WHERE id = ?`, id) + err := s.ro.GetContext(ctx, &t, s.ro.Rebind(`SELECT * FROM automation_triggers WHERE id = ?`), id) if errors.Is(err, sql.ErrNoRows) { return fmt.Errorf("trigger not found: %s", id) } @@ -1056,22 +1058,22 @@ func (s *Store) UpdateTrigger(ctx context.Context, id string, req *UpdateTrigger t.Enabled = *req.Enabled } t.UpdatedAt = time.Now().UTC() - _, err = s.db.ExecContext(ctx, - `UPDATE automation_triggers SET config = ?, enabled = ?, updated_at = ? WHERE id = ?`, + _, err = s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE automation_triggers SET config = ?, enabled = ?, updated_at = ? WHERE id = ?`), t.ConfigJSON, t.Enabled, t.UpdatedAt, id) return err } // DeleteTrigger removes a trigger. func (s *Store) DeleteTrigger(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM automation_triggers WHERE id = ?`, id) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM automation_triggers WHERE id = ?`), id) return err } // UpdateTriggerEvaluatedAt sets the last_evaluated_at timestamp. func (s *Store) UpdateTriggerEvaluatedAt(ctx context.Context, id string, t time.Time) error { - _, err := s.db.ExecContext(ctx, - `UPDATE automation_triggers SET last_evaluated_at = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE automation_triggers SET last_evaluated_at = ?, updated_at = ? WHERE id = ?`), t, time.Now().UTC(), id) return err } @@ -1079,11 +1081,11 @@ func (s *Store) UpdateTriggerEvaluatedAt(ctx context.Context, id string, t time. // ListEnabledTriggersByType returns enabled triggers of a specific type (across all enabled automations). func (s *Store) ListEnabledTriggersByType(ctx context.Context, triggerType TriggerType) ([]AutomationTrigger, error) { var triggers []AutomationTrigger - err := s.ro.SelectContext(ctx, &triggers, ` + err := s.ro.SelectContext(ctx, &triggers, s.ro.Rebind(` SELECT t.* FROM automation_triggers t JOIN automations a ON a.id = t.automation_id - WHERE t.type = ? AND t.enabled = 1 AND a.enabled = 1 - ORDER BY t.created_at ASC, t.id ASC`, string(triggerType)) + WHERE t.type = ? AND t.enabled = TRUE AND a.enabled = TRUE + ORDER BY t.created_at ASC, t.id ASC`), string(triggerType)) hydrateTriggers(triggers) return triggers, err } @@ -1097,11 +1099,11 @@ func (s *Store) CreateRun(ctx context.Context, r *AutomationRun) error { } r.CreatedAt = time.Now().UTC() r.TriggerDataJSON = string(r.TriggerData) - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO automation_runs (id, automation_id, trigger_id, trigger_type, task_id, status, dedup_key, trigger_data, error_message, session_id, turn_id, thread_action, thread_reason, display_title, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`), r.ID, r.AutomationID, r.TriggerID, r.TriggerType, r.TaskID, r.Status, r.DedupKey, r.TriggerDataJSON, r.ErrorMessage, r.SessionID, r.TurnID, r.ThreadAction, r.ThreadReason, r.DisplayTitle, r.CreatedAt) @@ -1116,14 +1118,14 @@ func (s *Store) AdoptTriggeredRun(ctx context.Context, r *AutomationRun) (bool, if r == nil || r.DedupKey == "" { return false, nil } - res, err := s.db.ExecContext(ctx, ` + res, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE automation_runs SET task_id = ?, status = ?, trigger_data = ?, error_message = ?, session_id = ?, turn_id = ?, thread_action = ?, thread_reason = ?, display_title = ? WHERE id = ( SELECT id FROM automation_runs WHERE automation_id = ? AND dedup_key = ? AND status = ? ORDER BY created_at DESC, id DESC LIMIT 1 - ) AND status = ?`, + ) AND status = ?`), r.TaskID, r.Status, r.TriggerDataJSON, r.ErrorMessage, r.SessionID, r.TurnID, r.ThreadAction, r.ThreadReason, r.DisplayTitle, r.AutomationID, r.DedupKey, string(RunStatusTriggered), string(RunStatusTriggered)) @@ -1138,9 +1140,9 @@ func (s *Store) AdoptTriggeredRun(ctx context.Context, r *AutomationRun) (bool, // run in triggered state. This closes the task ownership gap before the agent // session is ready, so a failed launch can still settle the exact run. func (s *Store) BindRunTask(ctx context.Context, runID, taskID string) error { - res, err := s.db.ExecContext(ctx, ` + res, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE automation_runs SET task_id = ? - WHERE id = ? AND status = ?`, taskID, runID, string(RunStatusTriggered)) + WHERE id = ? AND status = ?`), taskID, runID, string(RunStatusTriggered)) if err != nil { return err } @@ -1151,8 +1153,8 @@ func (s *Store) BindRunTask(ctx context.Context, runID, taskID string) error { } func (s *Store) SetContinuationTaskID(ctx context.Context, automationID, taskID string) error { - _, err := s.db.ExecContext(ctx, - `UPDATE automations SET continuation_task_id = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE automations SET continuation_task_id = ?, updated_at = ? WHERE id = ?`), taskID, time.Now().UTC(), automationID) return err } @@ -1161,10 +1163,10 @@ func (s *Store) SetContinuationTaskID(ctx context.Context, automationID, taskID // task_created. The identity is kept on the row so shared-task completion can // never settle a different firing. func (s *Store) BindRun(ctx context.Context, runID, taskID, sessionID, turnID string, action ThreadAction, reason string) error { - res, err := s.db.ExecContext(ctx, ` + res, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE automation_runs SET task_id = ?, session_id = ?, turn_id = ?, thread_action = ?, thread_reason = ?, status = ? - WHERE id = ? AND status IN (?, ?)`, + WHERE id = ? AND status IN (?, ?)`), taskID, sessionID, turnID, action, reason, string(RunStatusTaskCreated), runID, string(RunStatusTriggered), string(RunStatusTaskCreated)) if err != nil { @@ -1190,7 +1192,7 @@ func (s *Store) MarkRunTerminal(ctx context.Context, runID, sessionID, turnID st query += ` AND turn_id = ?` args = append(args, turnID) } - res, err := s.db.ExecContext(ctx, query, args...) + res, err := s.db.ExecContext(ctx, s.db.Rebind(query), args...) if err != nil { return err } @@ -1207,9 +1209,9 @@ func (s *Store) MarkRunTerminalByBinding(ctx context.Context, taskID, sessionID, if taskID == "" || sessionID == "" || turnID == "" { return fmt.Errorf("exact automation run binding is required") } - res, err := s.db.ExecContext(ctx, ` + res, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE automation_runs SET status = ?, error_message = ? - WHERE task_id = ? AND session_id = ? AND turn_id = ? AND status = ?`, + WHERE task_id = ? AND session_id = ? AND turn_id = ? AND status = ?`), string(status), errMsg, taskID, sessionID, turnID, string(RunStatusTaskCreated)) if err != nil { return err @@ -1240,13 +1242,13 @@ func (s *Store) updateRunTerminalStatus(ctx context.Context, taskID string, stat if taskID == "" { return nil } - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE automation_runs SET status = ?, error_message = ? WHERE id = ( SELECT id FROM automation_runs WHERE task_id = ? AND status = ? ORDER BY created_at DESC LIMIT 1 - )`, + )`), string(status), errMsg, taskID, string(RunStatusTaskCreated)) return err } @@ -1316,7 +1318,7 @@ func (s *Store) hydrateRunSummaries(ctx context.Context, runs []*AutomationRun) args[i] = turnID } var summaries []runSummaryRow - err := s.ro.SelectContext(ctx, &summaries, ` + err := s.ro.SelectContext(ctx, &summaries, s.ro.Rebind(` SELECT m.turn_id, substr(m.content, 1, 280) AS summary FROM task_session_messages m WHERE m.turn_id IN (`+placeholders+`) @@ -1325,9 +1327,9 @@ func (s *Store) hydrateRunSummaries(ctx context.Context, runs []*AutomationRun) SELECT 1 FROM task_session_messages newer WHERE newer.turn_id = m.turn_id AND newer.author_type = 'agent' AND newer.type = 'message' - AND (newer.created_at > m.created_at OR - (newer.created_at = m.created_at AND newer.id > m.id)) - )`, args...) + AND (newer.created_at > m.created_at OR + (newer.created_at = m.created_at AND newer.id > m.id)) + )`), args...) if db.IsMissingTableError(err) { return nil } @@ -1420,7 +1422,7 @@ const runTaskStateColumnsSQL = ` -- one query instead of one per run on the client. COALESCE(NULLIF(ar.session_id, ''), ( SELECT ts.id FROM task_sessions ts - WHERE ts.task_id = ar.task_id AND ts.is_primary = 1 + WHERE ts.task_id = ar.task_id AND ts.is_primary = 1 LIMIT 1 ), ar.session_id, '') AS session_id` @@ -1437,20 +1439,20 @@ func runTaskStateArgs() []any { func (s *Store) listRunsWithTaskState(ctx context.Context, automationID string, limit int) ([]*AutomationRun, error) { var runs []*AutomationRun - err := s.ro.SelectContext(ctx, &runs, ` + err := s.ro.SelectContext(ctx, &runs, s.ro.Rebind(` SELECT`+runTaskStateColumnsSQL+` FROM automation_runs ar LEFT JOIN tasks t ON t.id = ar.task_id WHERE ar.automation_id = ? - ORDER BY `+runOrderSQL("ar")+` LIMIT ?`, + ORDER BY `+runOrderSQL("ar")+` LIMIT ?`), append(runTaskStateArgs(), automationID, limit)...) return runs, err } func (s *Store) listRunsRaw(ctx context.Context, automationID string, limit int) ([]*AutomationRun, error) { var runs []*AutomationRun - err := s.ro.SelectContext(ctx, &runs, - `SELECT * FROM automation_runs WHERE automation_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`, + err := s.ro.SelectContext(ctx, &runs, s.ro.Rebind( + `SELECT * FROM automation_runs WHERE automation_id = ? ORDER BY created_at DESC, id DESC LIMIT ?`), automationID, limit) return runs, err } @@ -1504,14 +1506,14 @@ func (s *Store) listWorkspaceRunsWithTaskState(ctx context.Context, workspaceID // automation is gone can't be attributed to anything the reader can // open, and the ON DELETE CASCADE means it shouldn't exist anyway. var runs []*WorkspaceAutomationRun - err := s.ro.SelectContext(ctx, &runs, ` + err := s.ro.SelectContext(ctx, &runs, s.ro.Rebind(` SELECT`+runTaskStateColumnsSQL+`, a.name AS automation_name FROM automation_runs ar JOIN automations a ON a.id = ar.automation_id LEFT JOIN tasks t ON t.id = ar.task_id WHERE a.workspace_id = ? - ORDER BY `+runOrderSQL("ar")+` LIMIT ?`, + ORDER BY `+runOrderSQL("ar")+` LIMIT ?`), append(runTaskStateArgs(), workspaceID, limit)...) return runs, err } @@ -1607,13 +1609,13 @@ func (s *Store) selectSummaries(ctx context.Context, scope string, arg any) ([]s args := runTaskStateArgs() args = append(args, openRunArgs()...) args = append(args, arg) - err := s.ro.SelectContext(ctx, &rows, ` + err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind(` SELECT`+runTaskStateColumnsSQL+`, `+openRunsSubquerySQL+` FROM automation_runs ar JOIN automations a ON a.id = ar.automation_id LEFT JOIN tasks t ON t.id = ar.task_id - WHERE `+scope+` AND `+latestRunPerAutomationSQL, + WHERE `+scope+` AND `+latestRunPerAutomationSQL), args...) return rows, err } @@ -1624,26 +1626,26 @@ func (s *Store) selectSummaries(ctx context.Context, scope string, arg any) ([]s // open count is a plain status match. func (s *Store) selectSummariesRaw(ctx context.Context, scope string, arg any) ([]summaryRow, error) { var rows []summaryRow - err := s.ro.SelectContext(ctx, &rows, ` + err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind(` SELECT ar.*, ( SELECT COUNT(*) FROM automation_runs aro WHERE aro.automation_id = ar.automation_id AND aro.status IN (?, ?) ) AS open_runs FROM automation_runs ar JOIN automations a ON a.id = ar.automation_id - WHERE `+scope+` AND `+latestRunPerAutomationSQL, + WHERE `+scope+` AND `+latestRunPerAutomationSQL), string(RunStatusTriggered), string(RunStatusTaskCreated), arg) return rows, err } func (s *Store) listWorkspaceRunsRaw(ctx context.Context, workspaceID string, limit int) ([]*WorkspaceAutomationRun, error) { var runs []*WorkspaceAutomationRun - err := s.ro.SelectContext(ctx, &runs, ` + err := s.ro.SelectContext(ctx, &runs, s.ro.Rebind(` SELECT ar.*, a.name AS automation_name FROM automation_runs ar JOIN automations a ON a.id = ar.automation_id WHERE a.workspace_id = ? - ORDER BY `+runOrderSQL("ar")+` LIMIT ?`, + ORDER BY `+runOrderSQL("ar")+` LIMIT ?`), workspaceID, limit) return runs, err } @@ -1654,8 +1656,8 @@ func (s *Store) HasRunWithDedupKey(ctx context.Context, automationID, dedupKey s return false, nil } var count int - err := s.ro.GetContext(ctx, &count, - `SELECT COUNT(*) FROM automation_runs WHERE automation_id = ? AND dedup_key = ?`, + err := s.ro.GetContext(ctx, &count, s.ro.Rebind( + `SELECT COUNT(*) FROM automation_runs WHERE automation_id = ? AND dedup_key = ?`), automationID, dedupKey) return count > 0, err } @@ -1694,7 +1696,7 @@ const openRunPredicateSQL = `( OR (ar.status = ? AND t.id IS NOT NULL AND t.archived_at IS NULL AND NOT EXISTS ( SELECT 1 FROM task_sessions ts - WHERE ts.task_id = ar.task_id AND ts.is_primary = 1 AND ts.state = ? + WHERE ts.task_id = ar.task_id AND ts.is_primary = 1 AND ts.state = ? ) ))` @@ -1725,18 +1727,18 @@ func openRunArgs() []any { func (s *Store) countActiveRunsWithTaskState(ctx context.Context, automationID string) (int, error) { var count int - err := s.ro.GetContext(ctx, &count, ` + err := s.ro.GetContext(ctx, &count, s.ro.Rebind(` SELECT COUNT(*) FROM automation_runs ar LEFT JOIN tasks t ON t.id = ar.task_id - WHERE ar.automation_id = ? AND `+openRunPredicateSQL, + WHERE ar.automation_id = ? AND `+openRunPredicateSQL), append([]any{automationID}, openRunArgs()...)...) return count, err } func (s *Store) countActiveRunsRaw(ctx context.Context, automationID string) (int, error) { var count int - err := s.ro.GetContext(ctx, &count, - `SELECT COUNT(*) FROM automation_runs WHERE automation_id = ? AND status IN (?, ?)`, + err := s.ro.GetContext(ctx, &count, s.ro.Rebind( + `SELECT COUNT(*) FROM automation_runs WHERE automation_id = ? AND status IN (?, ?)`), automationID, string(RunStatusTriggered), string(RunStatusTaskCreated)) return count, err } @@ -1744,8 +1746,8 @@ func (s *Store) countActiveRunsRaw(ctx context.Context, automationID string) (in // GetRun returns a single run by ID, or nil if not found. func (s *Store) GetRun(ctx context.Context, id string) (*AutomationRun, error) { var r AutomationRun - err := s.ro.GetContext(ctx, &r, - `SELECT * FROM automation_runs WHERE id = ?`, id) + err := s.ro.GetContext(ctx, &r, s.ro.Rebind( + `SELECT * FROM automation_runs WHERE id = ?`), id) if err != nil { if errors.Is(err, sql.ErrNoRows) { return nil, nil @@ -1758,7 +1760,7 @@ func (s *Store) GetRun(ctx context.Context, id string) (*AutomationRun, error) { // DeleteRun removes a single run row. func (s *Store) DeleteRun(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM automation_runs WHERE id = ?`, id) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM automation_runs WHERE id = ?`), id) return err } @@ -1766,15 +1768,15 @@ func (s *Store) DeleteRun(ctx context.Context, id string) error { // Used by DeleteAllRuns so the service can clean up tasks before purging rows. func (s *Store) ListRunTaskIDs(ctx context.Context, automationID string) ([]string, error) { var ids []string - err := s.ro.SelectContext(ctx, &ids, - `SELECT DISTINCT task_id FROM automation_runs WHERE automation_id = ? AND task_id != ''`, + err := s.ro.SelectContext(ctx, &ids, s.ro.Rebind( + `SELECT DISTINCT task_id FROM automation_runs WHERE automation_id = ? AND task_id != ''`), automationID) return ids, err } // DeleteAllRuns removes every run row for an automation. func (s *Store) DeleteAllRuns(ctx context.Context, automationID string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM automation_runs WHERE automation_id = ?`, automationID) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM automation_runs WHERE automation_id = ?`), automationID) return err } @@ -1787,12 +1789,12 @@ func (s *Store) ClearContinuationAndDeleteAllRuns(ctx context.Context, automatio return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, - `UPDATE automations SET continuation_task_id = '', updated_at = ? WHERE id = ?`, time.Now().UTC(), automationID); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind( + `UPDATE automations SET continuation_task_id = '', updated_at = ? WHERE id = ?`), time.Now().UTC(), automationID); err != nil { return err } - if _, err := tx.ExecContext(ctx, - `DELETE FROM automation_runs WHERE automation_id = ?`, automationID); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind( + `DELETE FROM automation_runs WHERE automation_id = ?`), automationID); err != nil { return err } return tx.Commit() @@ -1803,18 +1805,18 @@ func (s *Store) ClearContinuationAndDeleteAllRuns(ctx context.Context, automatio func (s *Store) DeleteAutomationsByWorkspace(ctx context.Context, workspaceID string) (int, error) { // Get automation IDs first for cascade cleanup. var ids []string - if err := s.ro.SelectContext(ctx, &ids, - `SELECT id FROM automations WHERE workspace_id = ?`, workspaceID); err != nil { + if err := s.ro.SelectContext(ctx, &ids, s.ro.Rebind( + `SELECT id FROM automations WHERE workspace_id = ?`), workspaceID); err != nil { return 0, err } if len(ids) == 0 { return 0, nil } for _, id := range ids { - _, _ = s.db.ExecContext(ctx, `DELETE FROM automation_triggers WHERE automation_id = ?`, id) - _, _ = s.db.ExecContext(ctx, `DELETE FROM automation_runs WHERE automation_id = ?`, id) + _, _ = s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM automation_triggers WHERE automation_id = ?`), id) + _, _ = s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM automation_runs WHERE automation_id = ?`), id) } - res, err := s.db.ExecContext(ctx, `DELETE FROM automations WHERE workspace_id = ?`, workspaceID) + res, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM automations WHERE workspace_id = ?`), workspaceID) if err != nil { return 0, err } @@ -1822,6 +1824,17 @@ func (s *Store) DeleteAutomationsByWorkspace(ctx context.Context, workspaceID st return int(n), nil } +func schemaSQLForDriver(schema, driver string) string { + schema = strings.ReplaceAll(schema, "DATETIME", dialect.TimestampType(driver)) + if dialect.IsPostgres(driver) { + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 1", "BOOLEAN NOT NULL DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 0", "BOOLEAN NOT NULL DEFAULT FALSE") + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 1", "BOOLEAN DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 0", "BOOLEAN DEFAULT FALSE") + } + return schema +} + // generateSecret creates a random hex string for webhook authentication. func generateSecret() string { b := make([]byte, 16) diff --git a/apps/backend/internal/automation/store_postgres_test.go b/apps/backend/internal/automation/store_postgres_test.go new file mode 100644 index 0000000000..107abc2698 --- /dev/null +++ b/apps/backend/internal/automation/store_postgres_test.go @@ -0,0 +1,187 @@ +package automation + +import ( + "encoding/json" + "testing" + "time" + + "github.com/kandev/kandev/internal/testutil" +) + +func TestPostgresStoreSchemaReplay(t *testing.T) { + database := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t)) + if _, err := database.Exec(` + CREATE TABLE tasks ( + id TEXT PRIMARY KEY, + archived_at TIMESTAMPTZ + ); + CREATE TABLE task_sessions ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL, + is_primary INTEGER NOT NULL DEFAULT 0, + state TEXT NOT NULL + ); + CREATE TABLE task_session_messages ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL, + turn_id TEXT NOT NULL, + author_type TEXT NOT NULL, + content TEXT NOT NULL, + type TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL + ); + CREATE TABLE task_environments ( + id TEXT PRIMARY KEY, + task_id TEXT NOT NULL + ); + CREATE TABLE task_environment_repos ( + id TEXT PRIMARY KEY, + task_environment_id TEXT NOT NULL, + status TEXT NOT NULL + )`); err != nil { + t.Fatalf("create task prerequisites: %v", err) + } + if _, err := database.Exec(` + INSERT INTO tasks (id, archived_at) VALUES ('task-1', NULL); + INSERT INTO task_sessions (id, task_id, is_primary, state) + VALUES ('session-1', 'task-1', 1, 'RUNNING'); + INSERT INTO task_environments (id, task_id) VALUES ('environment-1', 'task-1'); + INSERT INTO task_environment_repos (id, task_environment_id, status) + VALUES ('environment-repo-1', 'environment-1', 'active')`); err != nil { + t.Fatalf("seed task prerequisites: %v", err) + } + + if _, err := NewStore(database, database); err != nil { + t.Fatalf("first automation store schema init: %v", err) + } + store, err := NewStore(database, database) + if err != nil { + t.Fatalf("second automation store schema init: %v", err) + } + + ctx := t.Context() + automation := &Automation{ + ID: "automation-postgres", + WorkspaceID: "ws-1", + Name: "PostgreSQL parity", + WorkflowID: "workflow-1", + WorkflowStepID: "step-1", + AgentProfileID: "agent-1", + ExecutorProfileID: "executor-1", + Prompt: "Review the change", + Enabled: true, + MaxConcurrentRuns: 2, + RepositoryMode: RepositoryModeSelected, + Repositories: []AutomationRepository{ + {RepositoryID: "repo-a", BaseBranch: "main"}, + {RepositoryID: "repo-b", BaseBranch: "develop"}, + }, + } + if err := store.CreateAutomation(ctx, automation); err != nil { + t.Fatalf("create automation: %v", err) + } + gotAutomation, err := store.GetAutomation(ctx, automation.ID) + if err != nil || gotAutomation == nil || len(gotAutomation.Repositories) != 2 || gotAutomation.Repositories[1].BaseBranch != "develop" { + t.Fatalf("get automation = %+v, err %v", gotAutomation, err) + } + if automations, err := store.ListAutomations(ctx, "ws-1"); err != nil || len(automations) != 1 { + t.Fatalf("list automations = %+v, err %v", automations, err) + } + if enabled, err := store.ListEnabledByAgentProfile(ctx, "agent-1"); err != nil || len(enabled) != 1 { + t.Fatalf("list enabled automations = %+v, err %v", enabled, err) + } + + trigger := &AutomationTrigger{ + ID: "trigger-postgres", + AutomationID: automation.ID, + Type: TriggerTypeScheduled, + Config: json.RawMessage(`{"cron_expression":"0 9 * * *"}`), + Enabled: true, + } + if err := store.CreateTrigger(ctx, trigger); err != nil { + t.Fatalf("create trigger: %v", err) + } + if gotTrigger, err := store.GetTrigger(ctx, trigger.ID); err != nil || gotTrigger == nil || string(gotTrigger.Config) != string(trigger.Config) { + t.Fatalf("get trigger = %+v, err %v", gotTrigger, err) + } + if triggers, err := store.ListEnabledTriggersByType(ctx, TriggerTypeScheduled); err != nil || len(triggers) != 1 { + t.Fatalf("list enabled triggers = %+v, err %v", triggers, err) + } + + run := &AutomationRun{ + ID: "run-postgres", + AutomationID: automation.ID, + TriggerID: trigger.ID, + TriggerType: TriggerTypeScheduled, + TaskID: "task-1", + Status: RunStatusTaskCreated, + DedupKey: "dedup-postgres", + TriggerData: json.RawMessage(`{"source":"postgres"}`), + SessionID: "session-1", + TurnID: "turn-1", + } + if err := store.CreateRun(ctx, run); err != nil { + t.Fatalf("create run: %v", err) + } + if _, err := database.Exec(` + INSERT INTO task_session_messages (id, task_id, turn_id, author_type, content, type, created_at) + VALUES ('message-1', 'task-1', 'turn-1', 'agent', 'PostgreSQL run completed', 'message', $1)`, time.Now().UTC()); err != nil { + t.Fatalf("seed run summary: %v", err) + } + + runs, err := store.ListRuns(ctx, automation.ID, 20) + if err != nil || len(runs) != 1 || runs[0].Status != RunStatusTaskCreated || runs[0].Summary != "PostgreSQL run completed" { + t.Fatalf("list runs = %+v, err %v", runs, err) + } + workspaceRuns, err := store.ListWorkspaceRuns(ctx, "ws-1", 20) + if err != nil || len(workspaceRuns) != 1 || workspaceRuns[0].AutomationName != automation.Name { + t.Fatalf("list workspace runs = %+v, err %v", workspaceRuns, err) + } + if openRuns, err := store.ListOpenRuns(ctx, automation.ID); err != nil || len(openRuns) != 1 { + t.Fatalf("list open runs = %+v, err %v", openRuns, err) + } + if allOpenRuns, err := store.ListAllOpenRuns(ctx); err != nil || len(allOpenRuns) != 1 { + t.Fatalf("list all open runs = %+v, err %v", allOpenRuns, err) + } + if summaries, err := store.ListAutomationSummaries(ctx, "ws-1"); err != nil || len(summaries) != 1 || summaries[0].OpenRuns != 1 { + t.Fatalf("list automation summaries = %+v, err %v", summaries, err) + } + if count, err := store.CountActiveRuns(ctx, automation.ID); err != nil || count != 1 { + t.Fatalf("count active runs = %d, err %v", count, err) + } + if found, err := store.HasRunWithDedupKey(ctx, automation.ID, run.DedupKey); err != nil || !found { + t.Fatalf("has run with dedup key = %v, err %v", found, err) + } + if inUse, err := store.RunWorkspaceInUse(ctx, "task-1"); err != nil || !inUse { + t.Fatalf("run workspace in use = %v, err %v", inUse, err) + } + if taskIDs, err := store.PrunableRunTaskIDs(ctx, "task-1", 0); err != nil || len(taskIDs) != 0 { + t.Fatalf("prunable run task IDs = %v, err %v", taskIDs, err) + } + + cleanupRun := &AutomationRun{ + ID: "run-cleanup", + AutomationID: automation.ID, + TriggerID: trigger.ID, + TriggerType: TriggerTypeScheduled, + TaskID: "task-cleanup", + Status: RunStatusSucceeded, + TriggerData: json.RawMessage(`{}`), + } + if err := store.CreateRun(ctx, cleanupRun); err != nil { + t.Fatalf("create cleanup run: %v", err) + } + if jobs, err := store.DeleteAutomationWithCleanup(ctx, automation.ID, []string{"task-cleanup"}); err != nil || len(jobs) != 1 || jobs[0] != "task-cleanup" { + t.Fatalf("delete automation with cleanup = %v, err %v", jobs, err) + } + jobs, err := store.ListCleanupJobs(ctx) + if err != nil || len(jobs) != 1 || jobs[0].TaskID != "task-cleanup" { + t.Fatalf("list cleanup jobs = %+v, err %v", jobs, err) + } + if err := store.UpdateCleanupJobError(ctx, "task-cleanup", "cleanup failed"); err != nil { + t.Fatalf("update cleanup job error: %v", err) + } + if err := store.DeleteCleanupJob(ctx, "task-cleanup"); err != nil { + t.Fatalf("delete cleanup job: %v", err) + } +} diff --git a/apps/backend/internal/azuredevops/store.go b/apps/backend/internal/azuredevops/store.go index 496987a527..b0cf59fd98 100644 --- a/apps/backend/internal/azuredevops/store.go +++ b/apps/backend/internal/azuredevops/store.go @@ -5,9 +5,13 @@ import ( "database/sql" "errors" "fmt" + "strings" "time" "github.com/jmoiron/sqlx" + + dbutil "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/db/dialect" ) // Store persists Azure DevOps configuration and health, never credentials. @@ -175,7 +179,7 @@ func NewStore(writer, reader *sqlx.DB) (*Store, error) { reader = writer } store := &Store{db: writer, ro: reader} - if _, err := store.db.Exec(createConfigTableSQL); err != nil { + if _, err := store.db.Exec(schemaSQLForDriver(createConfigTableSQL, store.db.DriverName())); err != nil { return nil, fmt.Errorf("azure devops schema init: %w", err) } if err := store.ensureSavedViewsColumn(); err != nil { @@ -187,13 +191,13 @@ func NewStore(writer, reader *sqlx.DB) (*Store, error) { if err := store.ensureWorkspaceSettingsVersionColumn(); err != nil { return nil, fmt.Errorf("azure devops workspace settings version schema init: %w", err) } - if _, err := store.db.Exec(createTaskPRTableSQL); err != nil { + if _, err := store.db.Exec(schemaSQLForDriver(createTaskPRTableSQL, store.db.DriverName())); err != nil { return nil, fmt.Errorf("azure devops task PR schema init: %w", err) } - if _, err := store.db.Exec(createTaskWorkItemTableSQL); err != nil { + if _, err := store.db.Exec(schemaSQLForDriver(createTaskWorkItemTableSQL, store.db.DriverName())); err != nil { return nil, fmt.Errorf("azure devops task work item schema init: %w", err) } - if _, err := store.db.Exec(createWatchTablesSQL); err != nil { + if _, err := store.db.Exec(schemaSQLForDriver(createWatchTablesSQL, store.db.DriverName())); err != nil { return nil, fmt.Errorf("azure devops watcher schema init: %w", err) } return store, nil @@ -221,27 +225,14 @@ func (s *Store) ensureSavedViewsColumn() error { } func (s *Store) ensureConfigColumn(column, statement string) error { - rows, err := s.db.Query(`PRAGMA table_info(azure_devops_configs)`) + columns, err := dbutil.TableColumns(s.db, "azure_devops_configs") if err != nil { return err } - defer func() { _ = rows.Close() }() - for rows.Next() { - var cid int - var name, columnType string - var notNull, primaryKey int - var defaultValue any - if scanErr := rows.Scan(&cid, &name, &columnType, ¬Null, &defaultValue, &primaryKey); scanErr != nil { - return scanErr - } - if name == column { - return rows.Err() - } + if columns[column] { + return nil } - if err := rows.Err(); err != nil { - return err - } - _, err = s.db.Exec(statement) + _, err = s.db.Exec(schemaSQLForDriver(statement, s.db.DriverName())) return err } @@ -251,8 +242,8 @@ func (s *Store) GetConfig(ctx context.Context, workspaceID string) (*Config, err return nil, err } var cfg Config - err := s.ro.GetContext(ctx, &cfg, - `SELECT `+selectConfigColumns+` FROM azure_devops_configs WHERE workspace_id = ?`, workspaceID) + err := s.ro.GetContext(ctx, &cfg, s.ro.Rebind( + `SELECT `+selectConfigColumns+` FROM azure_devops_configs WHERE workspace_id = ?`), workspaceID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -276,7 +267,7 @@ func (s *Store) UpsertConfig(ctx context.Context, cfg *Config) error { cfg.CreatedAt = now } cfg.UpdatedAt = now - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO azure_devops_configs ( workspace_id, organization_url, default_project_id, default_project_name, auth_method, created_at, updated_at @@ -286,7 +277,7 @@ func (s *Store) UpsertConfig(ctx context.Context, cfg *Config) error { default_project_id = excluded.default_project_id, default_project_name = excluded.default_project_name, auth_method = excluded.auth_method, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), cfg.WorkspaceID, cfg.OrganizationURL, cfg.DefaultProjectID, cfg.DefaultProjectName, cfg.AuthMethod, cfg.CreatedAt, cfg.UpdatedAt) return err @@ -297,16 +288,16 @@ func (s *Store) DeleteConfig(ctx context.Context, workspaceID string) error { if err := validateWorkspaceID(workspaceID); err != nil { return err } - _, err := s.db.ExecContext(ctx, - `DELETE FROM azure_devops_configs WHERE workspace_id = ?`, workspaceID) + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `DELETE FROM azure_devops_configs WHERE workspace_id = ?`), workspaceID) return err } // ListConfigWorkspaceIDs returns all configured workspace IDs in stable order. func (s *Store) ListConfigWorkspaceIDs(ctx context.Context) ([]string, error) { var workspaceIDs []string - if err := s.ro.SelectContext(ctx, &workspaceIDs, - `SELECT workspace_id FROM azure_devops_configs ORDER BY workspace_id`); err != nil { + if err := s.ro.SelectContext(ctx, &workspaceIDs, s.ro.Rebind( + `SELECT workspace_id FROM azure_devops_configs ORDER BY workspace_id`)); err != nil { return nil, err } return workspaceIDs, nil @@ -323,10 +314,10 @@ func (s *Store) UpdateAuthHealth( if err := validateWorkspaceID(workspaceID); err != nil { return err } - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE azure_devops_configs SET last_checked_at = ?, last_ok = ?, last_error = ? - WHERE workspace_id = ?`, checkedAt, ok, errMsg, workspaceID) + WHERE workspace_id = ?`), checkedAt, ok, errMsg, workspaceID) return err } @@ -335,10 +326,10 @@ func (s *Store) ResetAuthHealth(ctx context.Context, workspaceID string) error { if err := validateWorkspaceID(workspaceID); err != nil { return err } - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE azure_devops_configs - SET last_checked_at = NULL, last_ok = 0, last_error = '' - WHERE workspace_id = ?`, workspaceID) + SET last_checked_at = NULL, last_ok = FALSE, last_error = '' + WHERE workspace_id = ?`), workspaceID) return err } @@ -347,8 +338,8 @@ func (s *Store) GetSavedViewsJSON(ctx context.Context, workspaceID string) (stri return "", err } var raw string - err := s.ro.GetContext(ctx, &raw, - `SELECT saved_views FROM azure_devops_configs WHERE workspace_id = ?`, workspaceID) + err := s.ro.GetContext(ctx, &raw, s.ro.Rebind( + `SELECT saved_views FROM azure_devops_configs WHERE workspace_id = ?`), workspaceID) if errors.Is(err, sql.ErrNoRows) { return "", ErrNotConfigured } @@ -359,9 +350,9 @@ func (s *Store) PutSavedViewsJSON(ctx context.Context, workspaceID, raw string) if err := validateWorkspaceID(workspaceID); err != nil { return err } - result, err := s.db.ExecContext(ctx, ` + result, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE azure_devops_configs SET saved_views = ?, updated_at = ? - WHERE workspace_id = ?`, raw, time.Now().UTC(), workspaceID) + WHERE workspace_id = ?`), raw, time.Now().UTC(), workspaceID) if err != nil { return err } @@ -386,9 +377,9 @@ func (s *Store) GetWorkspaceSettingsSnapshot(ctx context.Context, workspaceID st return WorkspaceSettingsSnapshot{}, err } var snapshot WorkspaceSettingsSnapshot - err := s.ro.GetContext(ctx, &snapshot, + err := s.ro.GetContext(ctx, &snapshot, s.ro.Rebind( `SELECT workspace_settings AS json, workspace_settings_version AS version - FROM azure_devops_configs WHERE workspace_id = ?`, workspaceID) + FROM azure_devops_configs WHERE workspace_id = ?`), workspaceID) if errors.Is(err, sql.ErrNoRows) { return WorkspaceSettingsSnapshot{}, ErrNotConfigured } @@ -404,10 +395,10 @@ func (s *Store) PutWorkspaceSettingsJSON(ctx context.Context, workspaceID, raw s if err := validateWorkspaceID(workspaceID); err != nil { return err } - result, err := s.db.ExecContext(ctx, ` + result, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE azure_devops_configs SET workspace_settings = ?, workspace_settings_version = workspace_settings_version + 1, updated_at = ? - WHERE workspace_id = ?`, raw, time.Now().UTC(), workspaceID) + WHERE workspace_id = ?`), raw, time.Now().UTC(), workspaceID) if err != nil { return err } @@ -427,10 +418,10 @@ func (s *Store) PutWorkspaceSettingsJSONIfVersion(ctx context.Context, workspace if err := validateWorkspaceID(workspaceID); err != nil { return false, err } - result, err := s.db.ExecContext(ctx, ` + result, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE azure_devops_configs SET workspace_settings = ?, workspace_settings_version = workspace_settings_version + 1, updated_at = ? - WHERE workspace_id = ? AND workspace_settings_version = ?`, raw, time.Now().UTC(), workspaceID, version) + WHERE workspace_id = ? AND workspace_settings_version = ?`), raw, time.Now().UTC(), workspaceID, version) if err != nil { return false, err } @@ -441,3 +432,15 @@ func workspaceSettingsRowsUpdated(result sql.Result) (bool, error) { updated, err := result.RowsAffected() return updated > 0, err } + +func schemaSQLForDriver(schema, driver string) string { + schema = strings.ReplaceAll(schema, "TIMESTAMP", dialect.TimestampType(driver)) + schema = strings.ReplaceAll(schema, "DATETIME", dialect.TimestampType(driver)) + if dialect.IsPostgres(driver) { + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 1", "BOOLEAN NOT NULL DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 0", "BOOLEAN NOT NULL DEFAULT FALSE") + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 1", "BOOLEAN DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 0", "BOOLEAN DEFAULT FALSE") + } + return schema +} diff --git a/apps/backend/internal/azuredevops/store_postgres_test.go b/apps/backend/internal/azuredevops/store_postgres_test.go new file mode 100644 index 0000000000..f61c841fa5 --- /dev/null +++ b/apps/backend/internal/azuredevops/store_postgres_test.go @@ -0,0 +1,229 @@ +package azuredevops + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/kandev/kandev/internal/testutil" +) + +func TestPostgresStoreSchemaReplay(t *testing.T) { + ctx := context.Background() + database := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t)) + if _, err := database.Exec(` + CREATE TABLE tasks ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL + ); + INSERT INTO tasks (id, workspace_id) VALUES ('task-1', 'ws-1')`); err != nil { + t.Fatalf("create task prerequisite: %v", err) + } + + store, err := NewStore(database, database) + if err != nil { + t.Fatalf("first Azure DevOps store schema init: %v", err) + } + replayed, err := NewStore(database, database) + if err != nil { + t.Fatalf("second Azure DevOps store schema init: %v", err) + } + + config := &Config{ + WorkspaceID: "ws-1", + OrganizationURL: "https://dev.azure.com/acme", + DefaultProjectID: "project-1", + DefaultProjectName: "Platform", + AuthMethod: AuthMethodPAT, + } + if err := replayed.UpsertConfig(ctx, config); err != nil { + t.Fatalf("upsert Azure DevOps config: %v", err) + } + checkedAt := time.Now().UTC().Truncate(time.Microsecond) + if err := replayed.UpdateAuthHealth(ctx, "ws-1", true, "", checkedAt); err != nil { + t.Fatalf("update Azure DevOps auth health: %v", err) + } + if err := replayed.PutSavedViewsJSON(ctx, "ws-1", `[{"id":"view-1"}]`); err != nil { + t.Fatalf("put Azure DevOps saved views: %v", err) + } + if err := replayed.PutWorkspaceSettingsJSON(ctx, "ws-1", `{"workItemActions":[]}`); err != nil { + t.Fatalf("put Azure DevOps workspace settings: %v", err) + } + snapshot, err := replayed.GetWorkspaceSettingsSnapshot(ctx, "ws-1") + if err != nil || snapshot.JSON != `{"workItemActions":[]}` || snapshot.Version != 1 { + t.Fatalf("workspace settings snapshot = %+v, err=%v", snapshot, err) + } + updated, err := replayed.PutWorkspaceSettingsJSONIfVersion(ctx, "ws-1", `{"pullRequestActions":[]}`, snapshot.Version) + if err != nil || !updated { + t.Fatalf("conditional workspace settings update = %v, err=%v", updated, err) + } + updated, err = replayed.PutWorkspaceSettingsJSONIfVersion(ctx, "ws-1", `{}`, snapshot.Version) + if err != nil || updated { + t.Fatalf("stale workspace settings update = %v, err=%v", updated, err) + } + gotConfig, err := replayed.GetConfig(ctx, "ws-1") + if err != nil || gotConfig == nil || !gotConfig.LastOK || gotConfig.LastCheckedAt == nil { + t.Fatalf("get Azure DevOps config = %+v, err=%v", gotConfig, err) + } + savedViews, err := replayed.GetSavedViewsJSON(ctx, "ws-1") + if err != nil || savedViews != `[{"id":"view-1"}]` { + t.Fatalf("saved views = %q, err=%v", savedViews, err) + } + if err := replayed.ResetAuthHealth(ctx, "ws-1"); err != nil { + t.Fatalf("reset Azure DevOps auth health: %v", err) + } + + taskPR := &TaskPR{ + TaskID: "task-1", + RepositoryID: "repo-1", + OrganizationURL: config.OrganizationURL, + ProjectID: "project-1", + AzureRepositoryID: "azure-repo-1", + PullRequestID: 42, + PullRequestURL: "https://dev.azure.com/acme/project/_git/repo/pullrequest/42", + Title: "Initial PR", + SourceBranch: "feature", + TargetBranch: "main", + AuthorID: "author-1", + AuthorName: "Ada", + Status: "active", + IsDraft: true, + } + if err := replayed.UpsertTaskPR(ctx, taskPR); err != nil { + t.Fatalf("upsert Azure DevOps task PR: %v", err) + } + firstPRID, firstPRCreatedAt := taskPR.ID, taskPR.CreatedAt + taskPR.Title = "Updated PR" + if err := replayed.UpsertTaskPR(ctx, taskPR); err != nil { + t.Fatalf("refresh Azure DevOps task PR: %v", err) + } + prs, err := replayed.ListTaskPRsByTask(ctx, "task-1") + if err != nil || len(prs) != 1 || prs[0].ID != firstPRID || !prs[0].CreatedAt.Equal(firstPRCreatedAt) || prs[0].Title != "Updated PR" || !prs[0].IsDraft { + t.Fatalf("Azure DevOps task PRs = %+v, err=%v", prs, err) + } + prsByWorkspace, err := replayed.ListTaskPRsByWorkspace(ctx, "ws-1") + if err != nil || len(prsByWorkspace["task-1"]) != 1 { + t.Fatalf("Azure DevOps task PRs by workspace = %+v, err=%v", prsByWorkspace, err) + } + + workItem := &TaskWorkItem{ + TaskID: "task-1", + WorkspaceID: "ws-1", + ProjectID: "project-1", + WorkItemID: 101, + WorkItemURL: "https://dev.azure.com/acme/project/_workitems/edit/101", + Title: "Initial work item", + State: "Active", + Type: "User Story", + } + if err := replayed.UpsertTaskWorkItem(ctx, workItem); err != nil { + t.Fatalf("upsert Azure DevOps task work item: %v", err) + } + itemsByWorkspace, err := replayed.ListTaskWorkItemsByWorkspace(ctx, "ws-1") + if err != nil || len(itemsByWorkspace["task-1"]) != 1 { + t.Fatalf("Azure DevOps task work items = %+v, err=%v", itemsByWorkspace, err) + } + belongs, err := replayed.TaskBelongsToWorkspace(ctx, "task-1", "ws-1") + if err != nil || !belongs { + t.Fatalf("task workspace ownership = %v, err=%v", belongs, err) + } + + workWatch := &WorkItemWatch{ + ID: "work-watch-1", + WorkspaceID: "ws-1", + WorkflowID: "workflow-1", + WorkflowStepID: "step-1", + ProjectID: "project-1", + WIQL: "SELECT [System.Id] FROM WorkItems", + RepositoryID: "repo-1", + BaseBranch: "main", + AgentProfileID: "agent-1", + ExecutorProfileID: "executor-1", + Prompt: "Fix {{title}}", + CleanupPolicy: CleanupPolicyAuto, + MaxInflightTasks: intPtr(2), + PollIntervalSeconds: 60, + } + if err := replayed.CreateWorkItemWatch(ctx, workWatch); err != nil { + t.Fatalf("create Azure DevOps work-item watch: %v", err) + } + if got, err := replayed.GetWorkItemWatch(ctx, workWatch.ID); err != nil || got == nil || got.WIQL != workWatch.WIQL { + t.Fatalf("get Azure DevOps work-item watch = %+v, err=%v", got, err) + } + if enabled, err := replayed.ListEnabledWorkItemWatches(ctx); err != nil || len(enabled) != 1 { + t.Fatalf("enabled Azure DevOps work-item watches = %d, err=%v", len(enabled), err) + } + if ok, err := replayed.ReserveWorkItemWatchTask(ctx, workWatch.ID, workWatch.Generation, "project-1", 101, workItem.WorkItemURL); err != nil || !ok { + t.Fatalf("reserve Azure DevOps work item = %v, err=%v", ok, err) + } + if ok, err := replayed.ReserveWorkItemWatchTask(ctx, workWatch.ID, workWatch.Generation, "project-1", 101, workItem.WorkItemURL); err != nil || ok { + t.Fatalf("duplicate Azure DevOps work item reservation = %v, err=%v", ok, err) + } + if err := replayed.AssignWorkItemWatchTaskID(ctx, workWatch.ID, workWatch.Generation, "project-1", 101, "task-1"); err != nil { + t.Fatalf("assign Azure DevOps work item reservation: %v", err) + } + reset, err := replayed.BeginWorkItemWatchReset(ctx, workWatch.ID) + if err != nil || reset.Generation != workWatch.Generation+1 || len(reset.TaskIDs) != 1 || reset.TaskIDs[0] != "task-1" { + t.Fatalf("Azure DevOps work-item watch reset = %+v, err=%v", reset, err) + } + if err := replayed.FinishWorkItemWatchReset(ctx, workWatch.ID, reset.Generation); err != nil { + t.Fatalf("finish Azure DevOps work-item watch reset: %v", err) + } + if ok, err := replayed.ReserveWorkItemWatchTask(ctx, workWatch.ID, reset.Generation, "project-1", 101, workItem.WorkItemURL); err != nil || !ok { + t.Fatalf("reserve Azure DevOps work item after reset = %v, err=%v", ok, err) + } + + pullRequestWatch := &PullRequestWatch{ + ID: "pr-watch-1", + WorkspaceID: "ws-1", + WorkflowID: "workflow-1", + WorkflowStepID: "step-1", + ProjectID: "project-1", + AzureRepositoryID: "azure-repo-1", + Status: "active", + RepositoryID: "repo-1", + BaseBranch: "main", + AgentProfileID: "agent-1", + ExecutorProfileID: "executor-1", + CleanupPolicy: CleanupPolicyAuto, + PollIntervalSeconds: 60, + } + if err := replayed.CreatePullRequestWatch(ctx, pullRequestWatch); err != nil { + t.Fatalf("create Azure DevOps pull-request watch: %v", err) + } + if ok, err := replayed.ReservePullRequestWatchTask(ctx, pullRequestWatch.ID, pullRequestWatch.Generation, "project-1", "azure-repo-1", 42, taskPR.PullRequestURL); err != nil || !ok { + t.Fatalf("reserve Azure DevOps pull request = %v, err=%v", ok, err) + } + if ok, err := replayed.ReservePullRequestWatchTask(ctx, pullRequestWatch.ID, pullRequestWatch.Generation, "project-1", "azure-repo-1", 42, taskPR.PullRequestURL); err != nil || ok { + t.Fatalf("duplicate Azure DevOps pull request reservation = %v, err=%v", ok, err) + } + if err := replayed.AssignPullRequestWatchTaskID(ctx, pullRequestWatch.ID, pullRequestWatch.Generation, "project-1", "azure-repo-1", 42, "task-1"); err != nil { + t.Fatalf("assign Azure DevOps pull request reservation: %v", err) + } + if err := replayed.DeleteWatchesByWorkspace(ctx, "ws-1"); err != nil { + t.Fatalf("delete Azure DevOps watches by workspace: %v", err) + } + if rows, err := replayed.ListWorkItemWatchTasks(ctx, workWatch.ID, reset.Generation); err != nil || len(rows) != 0 { + t.Fatalf("work-item reservations after workspace deletion = %+v, err=%v", rows, err) + } + if rows, err := replayed.ListPullRequestWatchTasks(ctx, pullRequestWatch.ID, pullRequestWatch.Generation); err != nil || len(rows) != 0 { + t.Fatalf("pull-request reservations after workspace deletion = %+v, err=%v", rows, err) + } + + if err := replayed.DeleteTaskPRsByTask(ctx, "task-1"); err != nil { + t.Fatalf("delete Azure DevOps task PRs: %v", err) + } + if err := replayed.DeleteTaskWorkItemsByTask(ctx, "task-1"); err != nil { + t.Fatalf("delete Azure DevOps task work items: %v", err) + } + if err := replayed.DeleteConfig(ctx, "ws-1"); err != nil { + t.Fatalf("delete Azure DevOps config: %v", err) + } + if got, err := store.GetConfig(ctx, "ws-1"); err != nil || got != nil { + t.Fatalf("config after delete = %+v, err=%v", got, err) + } + if err := replayed.ReleaseWorkItemWatchTask(ctx, workWatch.ID, reset.Generation, "project-1", 101); !errors.Is(err, ErrReservationNotFound) { + t.Fatalf("released deleted work-item reservation error = %v, want ErrReservationNotFound", err) + } +} diff --git a/apps/backend/internal/azuredevops/store_task_pr.go b/apps/backend/internal/azuredevops/store_task_pr.go index 77100eb103..894a282bc8 100644 --- a/apps/backend/internal/azuredevops/store_task_pr.go +++ b/apps/backend/internal/azuredevops/store_task_pr.go @@ -74,9 +74,9 @@ func (s *Store) UpsertTaskPR(ctx context.Context, taskPR *TaskPR) error { // ListTaskPRsByTask returns all associations for one task in creation order. func (s *Store) ListTaskPRsByTask(ctx context.Context, taskID string) ([]*TaskPR, error) { var rows []TaskPR - if err := s.ro.SelectContext(ctx, &rows, + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( `SELECT `+taskPRSelectColumns+` FROM azure_devops_task_prs - WHERE task_id = ? ORDER BY created_at ASC`, taskID); err != nil { + WHERE task_id = ? ORDER BY created_at ASC`), taskID); err != nil { return nil, err } return taskPRPointers(rows), nil @@ -95,10 +95,10 @@ func (s *Store) DeleteTaskPRsByTask(ctx context.Context, taskID string) error { // ListTaskPRsByWorkspace groups associations for tasks owned by one workspace. func (s *Store) ListTaskPRsByWorkspace(ctx context.Context, workspaceID string) (map[string][]*TaskPR, error) { var rows []TaskPR - if err := s.ro.SelectContext(ctx, &rows, + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( `SELECT `+qualifiedTaskPRSelectColumns+` FROM azure_devops_task_prs atp INNER JOIN tasks t ON atp.task_id = t.id - WHERE t.workspace_id = ? ORDER BY atp.created_at ASC`, workspaceID); err != nil { + WHERE t.workspace_id = ? ORDER BY atp.created_at ASC`), workspaceID); err != nil { return nil, err } grouped := make(map[string][]*TaskPR) diff --git a/apps/backend/internal/azuredevops/store_task_work_item.go b/apps/backend/internal/azuredevops/store_task_work_item.go index 9b07001ced..1c795a8739 100644 --- a/apps/backend/internal/azuredevops/store_task_work_item.go +++ b/apps/backend/internal/azuredevops/store_task_work_item.go @@ -36,7 +36,7 @@ func (s *Store) UpsertTaskWorkItem(ctx context.Context, row *TaskWorkItem) error func (s *Store) ListTaskWorkItemsByWorkspace(ctx context.Context, workspaceID string) (map[string][]*TaskWorkItem, error) { var rows []TaskWorkItem - if err := s.ro.SelectContext(ctx, &rows, `SELECT `+taskWorkItemColumns+` FROM azure_devops_task_work_items WHERE workspace_id = ? ORDER BY created_at ASC`, workspaceID); err != nil { + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind(`SELECT `+taskWorkItemColumns+` FROM azure_devops_task_work_items WHERE workspace_id = ? ORDER BY created_at ASC`), workspaceID); err != nil { return nil, err } result := make(map[string][]*TaskWorkItem) @@ -58,7 +58,7 @@ func (s *Store) DeleteTaskWorkItemsByWorkspace(ctx context.Context, workspaceID func (s *Store) TaskBelongsToWorkspace(ctx context.Context, taskID, workspaceID string) (bool, error) { var found string - err := s.ro.GetContext(ctx, &found, `SELECT workspace_id FROM tasks WHERE id = ?`, taskID) + err := s.ro.GetContext(ctx, &found, s.ro.Rebind(`SELECT workspace_id FROM tasks WHERE id = ?`), taskID) if err != nil { return false, err } diff --git a/apps/backend/internal/azuredevops/store_watch_reset.go b/apps/backend/internal/azuredevops/store_watch_reset.go index ec0a6413c3..8e5a27c2a0 100644 --- a/apps/backend/internal/azuredevops/store_watch_reset.go +++ b/apps/backend/internal/azuredevops/store_watch_reset.go @@ -21,7 +21,7 @@ func (s *Store) beginWatchReset(ctx context.Context, watchTable, taskTable, watc return nil, err } defer func() { _ = tx.Rollback() }() - result, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE %s SET generation = generation + 1, last_polled_at = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND deleting = 0`, watchTable), watchID) + result, err := tx.ExecContext(ctx, tx.Rebind(fmt.Sprintf(`UPDATE %s SET generation = generation + 1, last_polled_at = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND deleting = FALSE`, watchTable)), watchID) if err != nil { return nil, err } @@ -33,11 +33,11 @@ func (s *Store) beginWatchReset(ctx context.Context, watchTable, taskTable, watc return nil, ErrWatchNotFound } var generation int64 - if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT generation FROM %s WHERE id = ?`, watchTable), watchID).Scan(&generation); err != nil { + if err := tx.QueryRowxContext(ctx, tx.Rebind(fmt.Sprintf(`SELECT generation FROM %s WHERE id = ?`, watchTable)), watchID).Scan(&generation); err != nil { return nil, err } var taskIDs []string - if err := tx.SelectContext(ctx, &taskIDs, fmt.Sprintf(`SELECT task_id FROM %s WHERE watch_id = ? AND generation < ? AND task_id <> '' ORDER BY created_at`, taskTable), watchID, generation); err != nil && !errors.Is(err, sql.ErrNoRows) { + if err := tx.SelectContext(ctx, &taskIDs, tx.Rebind(fmt.Sprintf(`SELECT task_id FROM %s WHERE watch_id = ? AND generation < ? AND task_id <> '' ORDER BY created_at`, taskTable)), watchID, generation); err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, err } if err := tx.Commit(); err != nil { @@ -60,10 +60,10 @@ func (s *Store) finishWatchReset(ctx context.Context, watchTable, taskTable, wat return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM %s WHERE watch_id = ? AND generation < ?`, taskTable), watchID, generation); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(fmt.Sprintf(`DELETE FROM %s WHERE watch_id = ? AND generation < ?`, taskTable)), watchID, generation); err != nil { return err } - result, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE %s SET last_polled_at = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND generation = ? AND deleting = 0`, watchTable), watchID, generation) + result, err := tx.ExecContext(ctx, tx.Rebind(fmt.Sprintf(`UPDATE %s SET last_polled_at = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND generation = ? AND deleting = FALSE`, watchTable)), watchID, generation) if err != nil { return err } @@ -79,12 +79,12 @@ func (s *Store) finishWatchReset(ctx context.Context, watchTable, taskTable, wat func (s *Store) ListWorkItemWatchTaskIDs(ctx context.Context, watchID string) ([]string, error) { var ids []string - err := s.ro.SelectContext(ctx, &ids, `SELECT task_id FROM azure_devops_work_item_watch_tasks WHERE watch_id = ? AND task_id <> '' ORDER BY created_at`, watchID) + err := s.ro.SelectContext(ctx, &ids, s.ro.Rebind(`SELECT task_id FROM azure_devops_work_item_watch_tasks WHERE watch_id = ? AND task_id <> '' ORDER BY created_at`), watchID) return ids, err } func (s *Store) ListPullRequestWatchTaskIDs(ctx context.Context, watchID string) ([]string, error) { var ids []string - err := s.ro.SelectContext(ctx, &ids, `SELECT task_id FROM azure_devops_pull_request_watch_tasks WHERE watch_id = ? AND task_id <> '' ORDER BY created_at`, watchID) + err := s.ro.SelectContext(ctx, &ids, s.ro.Rebind(`SELECT task_id FROM azure_devops_pull_request_watch_tasks WHERE watch_id = ? AND task_id <> '' ORDER BY created_at`), watchID) return ids, err } diff --git a/apps/backend/internal/azuredevops/watch_store.go b/apps/backend/internal/azuredevops/watch_store.go index 48a0bff9a4..a3c3ca6b3b 100644 --- a/apps/backend/internal/azuredevops/watch_store.go +++ b/apps/backend/internal/azuredevops/watch_store.go @@ -68,13 +68,13 @@ func (s *Store) CreateWorkItemWatch(ctx context.Context, watch *WorkItemWatch) e watch.CreatedAt = now } watch.UpdatedAt = now - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO azure_devops_work_item_watches (id, workspace_id, workflow_id, workflow_step_id, project_id, wiql, repository_id, base_branch, agent_profile_id, executor_profile_id, prompt, enabled, poll_interval_seconds, cleanup_policy, max_inflight_tasks, generation, deleting, last_error, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`), watch.ID, watch.WorkspaceID, watch.WorkflowID, watch.WorkflowStepID, watch.ProjectID, watch.WIQL, watch.RepositoryID, watch.BaseBranch, watch.AgentProfileID, watch.ExecutorProfileID, watch.Prompt, watch.Enabled, @@ -85,12 +85,12 @@ func (s *Store) CreateWorkItemWatch(ctx context.Context, watch *WorkItemWatch) e func (s *Store) GetWorkItemWatch(ctx context.Context, id string) (*WorkItemWatch, error) { var watch WorkItemWatch - err := s.ro.GetContext(ctx, &watch, `SELECT id, workspace_id, workflow_id, + err := s.ro.GetContext(ctx, &watch, s.ro.Rebind(`SELECT id, workspace_id, workflow_id, workflow_step_id, project_id, wiql, repository_id, base_branch, agent_profile_id, executor_profile_id, prompt, enabled, poll_interval_seconds, cleanup_policy, max_inflight_tasks, generation, deleting, last_error, last_error_at, last_polled_at, created_at, updated_at - FROM azure_devops_work_item_watches WHERE id = ?`, id) + FROM azure_devops_work_item_watches WHERE id = ?`), id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -102,25 +102,25 @@ func (s *Store) GetWorkItemWatch(ctx context.Context, id string) (*WorkItemWatch func (s *Store) ListWorkItemWatches(ctx context.Context, workspaceID string) ([]*WorkItemWatch, error) { var watches []*WorkItemWatch - err := s.ro.SelectContext(ctx, &watches, `SELECT id, workspace_id, workflow_id, + err := s.ro.SelectContext(ctx, &watches, s.ro.Rebind(`SELECT id, workspace_id, workflow_id, workflow_step_id, project_id, wiql, repository_id, base_branch, agent_profile_id, executor_profile_id, prompt, enabled, poll_interval_seconds, cleanup_policy, max_inflight_tasks, generation, deleting, last_error, last_error_at, last_polled_at, created_at, updated_at - FROM azure_devops_work_item_watches WHERE workspace_id = ? AND deleting = 0 - ORDER BY created_at, id`, workspaceID) + FROM azure_devops_work_item_watches WHERE workspace_id = ? AND deleting = FALSE + ORDER BY created_at, id`), workspaceID) return watches, err } func (s *Store) ListEnabledWorkItemWatches(ctx context.Context) ([]*WorkItemWatch, error) { var watches []*WorkItemWatch - err := s.ro.SelectContext(ctx, &watches, `SELECT id, workspace_id, workflow_id, + err := s.ro.SelectContext(ctx, &watches, s.ro.Rebind(`SELECT id, workspace_id, workflow_id, workflow_step_id, project_id, wiql, repository_id, base_branch, agent_profile_id, executor_profile_id, prompt, enabled, poll_interval_seconds, cleanup_policy, max_inflight_tasks, generation, deleting, last_error, last_error_at, last_polled_at, created_at, updated_at - FROM azure_devops_work_item_watches WHERE enabled = 1 AND deleting = 0 - ORDER BY last_polled_at IS NOT NULL, last_polled_at, id`) + FROM azure_devops_work_item_watches WHERE enabled = TRUE AND deleting = FALSE + ORDER BY last_polled_at IS NOT NULL, last_polled_at, id`)) return watches, err } @@ -129,12 +129,12 @@ func (s *Store) UpdateWorkItemWatch(ctx context.Context, watch *WorkItemWatch) e return err } watch.UpdatedAt = time.Now().UTC() - result, err := s.db.ExecContext(ctx, `UPDATE azure_devops_work_item_watches SET + result, err := s.db.ExecContext(ctx, s.db.Rebind(`UPDATE azure_devops_work_item_watches SET workflow_id = ?, workflow_step_id = ?, project_id = ?, wiql = ?, repository_id = ?, base_branch = ?, agent_profile_id = ?, executor_profile_id = ?, prompt = ?, enabled = ?, poll_interval_seconds = ?, cleanup_policy = ?, max_inflight_tasks = ?, updated_at = ? - WHERE id = ? AND deleting = 0`, + WHERE id = ? AND deleting = FALSE`), watch.WorkflowID, watch.WorkflowStepID, watch.ProjectID, watch.WIQL, watch.RepositoryID, watch.BaseBranch, watch.AgentProfileID, watch.ExecutorProfileID, watch.Prompt, watch.Enabled, watch.PollIntervalSeconds, @@ -162,14 +162,14 @@ func (s *Store) CreatePullRequestWatch(ctx context.Context, watch *PullRequestWa watch.CreatedAt = now } watch.UpdatedAt = now - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO azure_devops_pull_request_watches (id, workspace_id, workflow_id, workflow_step_id, project_id, azure_repository_id, status, creator_id, reviewer_id, repository_id, base_branch, agent_profile_id, executor_profile_id, prompt, enabled, poll_interval_seconds, cleanup_policy, max_inflight_tasks, generation, deleting, last_error, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`), watch.ID, watch.WorkspaceID, watch.WorkflowID, watch.WorkflowStepID, watch.ProjectID, watch.AzureRepositoryID, watch.Status, watch.CreatorID, watch.ReviewerID, watch.RepositoryID, watch.BaseBranch, watch.AgentProfileID, @@ -181,13 +181,13 @@ func (s *Store) CreatePullRequestWatch(ctx context.Context, watch *PullRequestWa func (s *Store) GetPullRequestWatch(ctx context.Context, id string) (*PullRequestWatch, error) { var watch PullRequestWatch - err := s.ro.GetContext(ctx, &watch, `SELECT id, workspace_id, workflow_id, + err := s.ro.GetContext(ctx, &watch, s.ro.Rebind(`SELECT id, workspace_id, workflow_id, workflow_step_id, project_id, azure_repository_id, status, creator_id, reviewer_id, repository_id, base_branch, agent_profile_id, executor_profile_id, prompt, enabled, poll_interval_seconds, cleanup_policy, max_inflight_tasks, generation, deleting, last_error, last_error_at, last_polled_at, created_at, updated_at - FROM azure_devops_pull_request_watches WHERE id = ?`, id) + FROM azure_devops_pull_request_watches WHERE id = ?`), id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -199,27 +199,27 @@ func (s *Store) GetPullRequestWatch(ctx context.Context, id string) (*PullReques func (s *Store) ListPullRequestWatches(ctx context.Context, workspaceID string) ([]*PullRequestWatch, error) { var watches []*PullRequestWatch - err := s.ro.SelectContext(ctx, &watches, `SELECT id, workspace_id, workflow_id, + err := s.ro.SelectContext(ctx, &watches, s.ro.Rebind(`SELECT id, workspace_id, workflow_id, workflow_step_id, project_id, azure_repository_id, status, creator_id, reviewer_id, repository_id, base_branch, agent_profile_id, executor_profile_id, prompt, enabled, poll_interval_seconds, cleanup_policy, max_inflight_tasks, generation, deleting, last_error, last_error_at, last_polled_at, created_at, updated_at - FROM azure_devops_pull_request_watches WHERE workspace_id = ? AND deleting = 0 - ORDER BY created_at, id`, workspaceID) + FROM azure_devops_pull_request_watches WHERE workspace_id = ? AND deleting = FALSE + ORDER BY created_at, id`), workspaceID) return watches, err } func (s *Store) ListEnabledPullRequestWatches(ctx context.Context) ([]*PullRequestWatch, error) { var watches []*PullRequestWatch - err := s.ro.SelectContext(ctx, &watches, `SELECT id, workspace_id, workflow_id, + err := s.ro.SelectContext(ctx, &watches, s.ro.Rebind(`SELECT id, workspace_id, workflow_id, workflow_step_id, project_id, azure_repository_id, status, creator_id, reviewer_id, repository_id, base_branch, agent_profile_id, executor_profile_id, prompt, enabled, poll_interval_seconds, cleanup_policy, max_inflight_tasks, generation, deleting, last_error, last_error_at, last_polled_at, created_at, updated_at - FROM azure_devops_pull_request_watches WHERE enabled = 1 AND deleting = 0 - ORDER BY last_polled_at IS NOT NULL, last_polled_at, id`) + FROM azure_devops_pull_request_watches WHERE enabled = TRUE AND deleting = FALSE + ORDER BY last_polled_at IS NOT NULL, last_polled_at, id`)) return watches, err } @@ -228,12 +228,12 @@ func (s *Store) UpdatePullRequestWatch(ctx context.Context, watch *PullRequestWa return err } watch.UpdatedAt = time.Now().UTC() - result, err := s.db.ExecContext(ctx, `UPDATE azure_devops_pull_request_watches SET + result, err := s.db.ExecContext(ctx, s.db.Rebind(`UPDATE azure_devops_pull_request_watches SET workflow_id = ?, workflow_step_id = ?, project_id = ?, azure_repository_id = ?, status = ?, creator_id = ?, reviewer_id = ?, repository_id = ?, base_branch = ?, agent_profile_id = ?, executor_profile_id = ?, prompt = ?, enabled = ?, poll_interval_seconds = ?, cleanup_policy = ?, max_inflight_tasks = ?, - updated_at = ? WHERE id = ? AND deleting = 0`, + updated_at = ? WHERE id = ? AND deleting = FALSE`), watch.WorkflowID, watch.WorkflowStepID, watch.ProjectID, watch.AzureRepositoryID, watch.Status, watch.CreatorID, watch.ReviewerID, watch.RepositoryID, watch.BaseBranch, watch.AgentProfileID, watch.ExecutorProfileID, watch.Prompt, @@ -261,7 +261,7 @@ func (s *Store) SetPullRequestWatchError(ctx context.Context, id, message string } func (s *Store) setWatchError(ctx context.Context, table, id, message string, checkedAt time.Time) error { - _, err := s.db.ExecContext(ctx, fmt.Sprintf(`UPDATE %s SET last_error = ?, last_error_at = ?, last_polled_at = ?, updated_at = ? WHERE id = ? AND deleting = 0`, table), message, checkedAt, checkedAt, checkedAt, id) + _, err := s.db.ExecContext(ctx, s.db.Rebind(fmt.Sprintf(`UPDATE %s SET last_error = ?, last_error_at = ?, last_polled_at = ?, updated_at = ? WHERE id = ? AND deleting = FALSE`, table)), message, checkedAt, checkedAt, checkedAt, id) return err } @@ -274,7 +274,7 @@ func (s *Store) ClearPullRequestWatchError(ctx context.Context, id string, polle } func (s *Store) clearWatchError(ctx context.Context, table, id string, polledAt time.Time) error { - _, err := s.db.ExecContext(ctx, fmt.Sprintf(`UPDATE %s SET last_error = '', last_error_at = NULL, last_polled_at = ?, updated_at = ? WHERE id = ? AND deleting = 0`, table), polledAt, polledAt, id) + _, err := s.db.ExecContext(ctx, s.db.Rebind(fmt.Sprintf(`UPDATE %s SET last_error = '', last_error_at = NULL, last_polled_at = ?, updated_at = ? WHERE id = ? AND deleting = FALSE`, table)), polledAt, polledAt, id) return err } @@ -287,7 +287,7 @@ func (s *Store) DisablePullRequestWatchWithError(ctx context.Context, id, cause } func (s *Store) disableWatchWithError(ctx context.Context, table, id, cause string) error { - result, err := s.db.ExecContext(ctx, fmt.Sprintf(`UPDATE %s SET enabled = 0, last_error = ?, last_error_at = ?, updated_at = ? WHERE id = ? AND deleting = 0`, table), cause, time.Now().UTC(), time.Now().UTC(), id) + result, err := s.db.ExecContext(ctx, s.db.Rebind(fmt.Sprintf(`UPDATE %s SET enabled = FALSE, last_error = ?, last_error_at = ?, updated_at = ? WHERE id = ? AND deleting = FALSE`, table)), cause, time.Now().UTC(), time.Now().UTC(), id) if err != nil { return err } @@ -310,15 +310,15 @@ func (s *Store) DeletePullRequestWatch(ctx context.Context, id string) error { } func (s *Store) deleteWatch(ctx context.Context, watchTable, taskTable, id string) error { - tx, err := s.db.BeginTx(ctx, nil) + tx, err := s.db.BeginTxx(ctx, nil) if err != nil { return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM %s WHERE watch_id = ?`, taskTable), id); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(fmt.Sprintf(`DELETE FROM %s WHERE watch_id = ?`, taskTable)), id); err != nil { return err } - result, err := tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM %s WHERE id = ?`, watchTable), id) + result, err := tx.ExecContext(ctx, tx.Rebind(fmt.Sprintf(`DELETE FROM %s WHERE id = ?`, watchTable)), id) if err != nil { return err } @@ -333,17 +333,17 @@ func (s *Store) deleteWatch(ctx context.Context, watchTable, taskTable, id strin } func (s *Store) DeleteWorkItemWatchTasksByTask(ctx context.Context, taskID string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM azure_devops_work_item_watch_tasks WHERE task_id = ?`, taskID) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM azure_devops_work_item_watch_tasks WHERE task_id = ?`), taskID) return err } func (s *Store) DeletePullRequestWatchTasksByTask(ctx context.Context, taskID string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM azure_devops_pull_request_watch_tasks WHERE task_id = ?`, taskID) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM azure_devops_pull_request_watch_tasks WHERE task_id = ?`), taskID) return err } func (s *Store) DeleteWatchesByWorkspace(ctx context.Context, workspaceID string) error { - tx, err := s.db.BeginTx(ctx, nil) + tx, err := s.db.BeginTxx(ctx, nil) if err != nil { return err } @@ -357,7 +357,7 @@ func (s *Store) DeleteWatchesByWorkspace(ctx context.Context, workspaceID string `DELETE FROM azure_devops_work_item_watches WHERE workspace_id = ?`, `DELETE FROM azure_devops_pull_request_watches WHERE workspace_id = ?`, } { - if _, err := tx.ExecContext(ctx, query, workspaceID); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(query), workspaceID); err != nil { return err } } @@ -366,10 +366,10 @@ func (s *Store) DeleteWatchesByWorkspace(ctx context.Context, workspaceID string func (s *Store) ListWorkItemWatchTasks(ctx context.Context, watchID string, generation int64) ([]*WorkItemWatchTask, error) { var rows []WorkItemWatchTask - err := s.ro.SelectContext(ctx, &rows, `SELECT id, watch_id, project_id, work_item_id, + err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind(`SELECT id, watch_id, project_id, work_item_id, work_item_url, task_id, generation, created_at FROM azure_devops_work_item_watch_tasks - WHERE watch_id = ? AND generation = ? ORDER BY created_at`, watchID, generation) + WHERE watch_id = ? AND generation = ? ORDER BY created_at`), watchID, generation) if err != nil { return nil, err } @@ -382,10 +382,10 @@ func (s *Store) ListWorkItemWatchTasks(ctx context.Context, watchID string, gene func (s *Store) ListPullRequestWatchTasks(ctx context.Context, watchID string, generation int64) ([]*PullRequestWatchTask, error) { var rows []PullRequestWatchTask - err := s.ro.SelectContext(ctx, &rows, `SELECT id, watch_id, project_id, + err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind(`SELECT id, watch_id, project_id, azure_repository_id, pull_request_id, pull_request_url, task_id, generation, created_at FROM azure_devops_pull_request_watch_tasks - WHERE watch_id = ? AND generation = ? ORDER BY created_at`, watchID, generation) + WHERE watch_id = ? AND generation = ? ORDER BY created_at`), watchID, generation) if err != nil { return nil, err } @@ -397,12 +397,12 @@ func (s *Store) ListPullRequestWatchTasks(ctx context.Context, watchID string, g } func (s *Store) DeleteWorkItemWatchTask(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM azure_devops_work_item_watch_tasks WHERE id = ?`, id) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM azure_devops_work_item_watch_tasks WHERE id = ?`), id) return err } func (s *Store) DeletePullRequestWatchTask(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM azure_devops_pull_request_watch_tasks WHERE id = ?`, id) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM azure_devops_pull_request_watch_tasks WHERE id = ?`), id) return err } @@ -411,7 +411,7 @@ func (s *Store) ReserveWorkItemWatchTask(ctx context.Context, watchID string, ge INSERT INTO azure_devops_work_item_watch_tasks (id, watch_id, project_id, work_item_id, work_item_url, task_id, generation, created_at) SELECT ?, ?, ?, ?, ?, '', ?, ? WHERE EXISTS ( - SELECT 1 FROM azure_devops_work_item_watches WHERE id = ? AND generation = ? AND enabled = 1 AND deleting = 0 + SELECT 1 FROM azure_devops_work_item_watches WHERE id = ? AND generation = ? AND enabled = TRUE AND deleting = FALSE ) ON CONFLICT(watch_id, generation, project_id, work_item_id) DO NOTHING`, []any{uuid.NewString(), watchID, projectID, workItemID, workItemURL, generation, time.Now().UTC(), watchID, generation}) } @@ -429,7 +429,7 @@ func (s *Store) ReservePullRequestWatchTask(ctx context.Context, watchID string, INSERT INTO azure_devops_pull_request_watch_tasks (id, watch_id, project_id, azure_repository_id, pull_request_id, pull_request_url, task_id, generation, created_at) SELECT ?, ?, ?, ?, ?, ?, '', ?, ? WHERE EXISTS ( - SELECT 1 FROM azure_devops_pull_request_watches WHERE id = ? AND generation = ? AND enabled = 1 AND deleting = 0 + SELECT 1 FROM azure_devops_pull_request_watches WHERE id = ? AND generation = ? AND enabled = TRUE AND deleting = FALSE ) ON CONFLICT(watch_id, generation, project_id, azure_repository_id, pull_request_id) DO NOTHING`, []any{uuid.NewString(), watchID, projectID, azureRepositoryID, pullRequestID, pullRequestURL, generation, time.Now().UTC(), watchID, generation}) } @@ -443,7 +443,7 @@ func (s *Store) ReleasePullRequestWatchTask(ctx context.Context, watchID string, } func (s *Store) reserveWatchTask(ctx context.Context, table, query string, args []any) (bool, error) { - result, err := s.db.ExecContext(ctx, query, args...) + result, err := s.db.ExecContext(ctx, s.db.Rebind(query), args...) if err != nil { return false, err } @@ -454,7 +454,7 @@ func (s *Store) reserveWatchTask(ctx context.Context, table, query string, args func (s *Store) assignWatchTaskID(ctx context.Context, table, watchID string, generation int64, taskID, identity string, identityArgs ...any) error { args := []any{taskID, watchID, generation} args = append(args, identityArgs...) - result, err := s.db.ExecContext(ctx, fmt.Sprintf(`UPDATE %s SET task_id = ? WHERE watch_id = ? AND generation = ? AND %s`, table, identity), args...) + result, err := s.db.ExecContext(ctx, s.db.Rebind(fmt.Sprintf(`UPDATE %s SET task_id = ? WHERE watch_id = ? AND generation = ? AND %s`, table, identity)), args...) if err != nil { return err } @@ -475,7 +475,7 @@ func (s *Store) assignWatchTaskID(ctx context.Context, table, watchID string, ge func (s *Store) releaseWatchTask(ctx context.Context, table, watchID string, generation int64, identity string, identityArgs ...any) error { args := []any{watchID, generation} args = append(args, identityArgs...) - result, err := s.db.ExecContext(ctx, fmt.Sprintf(`DELETE FROM %s WHERE watch_id = ? AND generation = ? AND %s`, table, identity), args...) + result, err := s.db.ExecContext(ctx, s.db.Rebind(fmt.Sprintf(`DELETE FROM %s WHERE watch_id = ? AND generation = ? AND %s`, table, identity)), args...) if err != nil { return err } @@ -502,7 +502,7 @@ func (s *Store) watchGeneration(ctx context.Context, watchID string) (*watchGene `SELECT generation, deleting, enabled FROM azure_devops_pull_request_watches WHERE id = ?`, } for _, query := range queries { - err := s.ro.GetContext(ctx, &row, query, watchID) + err := s.ro.GetContext(ctx, &row, s.ro.Rebind(query), watchID) if err == nil { return &row, nil } diff --git a/apps/backend/internal/backendapp/postgres_boot_test.go b/apps/backend/internal/backendapp/postgres_boot_test.go index b5cdbb0113..fc53828626 100644 --- a/apps/backend/internal/backendapp/postgres_boot_test.go +++ b/apps/backend/internal/backendapp/postgres_boot_test.go @@ -87,6 +87,51 @@ func TestPostgresBootInitializesRepositories(t *testing.T) { if err != nil { t.Fatalf("provide services with postgres: %v", err) } + if services.GitHub == nil { + t.Fatal("GitHub service is unavailable after PostgreSQL boot") + } + if _, err := services.GitHub.GetWorkspaceSettings(context.Background(), "boot-workspace"); err != nil { + t.Fatalf("GitHub persistence is unavailable after PostgreSQL boot: %v", err) + } + if services.GitLab == nil { + t.Fatal("GitLab service is unavailable after PostgreSQL boot") + } + if _, err := services.GitLab.GetConfigForWorkspace(context.Background(), "boot-workspace"); err != nil { + t.Fatalf("GitLab task persistence is unavailable after PostgreSQL boot: %v", err) + } + if services.Jira == nil { + t.Fatal("Jira service is unavailable after PostgreSQL boot") + } + if _, err := services.Jira.GetConfigForWorkspace(context.Background(), "boot-workspace"); err != nil { + t.Fatalf("Jira persistence is unavailable after PostgreSQL boot: %v", err) + } + if services.Linear == nil { + t.Fatal("Linear service is unavailable after PostgreSQL boot") + } + if _, err := services.Linear.GetConfigForWorkspace(context.Background(), "boot-workspace"); err != nil { + t.Fatalf("Linear persistence is unavailable after PostgreSQL boot: %v", err) + } + if services.Sentry == nil || services.Sentry.Store() == nil { + t.Fatal("Sentry persistence is unavailable after PostgreSQL boot") + } + if _, err := services.Sentry.ListInstances(context.Background(), "boot-workspace"); err != nil { + t.Fatalf("Sentry persistence is unavailable after PostgreSQL boot: %v", err) + } + if services.AzureDevOps == nil { + t.Fatal("Azure DevOps service is unavailable after PostgreSQL boot") + } + if _, err := services.AzureDevOps.GetConfigForWorkspace(context.Background(), "boot-workspace"); err != nil { + t.Fatalf("Azure DevOps persistence is unavailable after PostgreSQL boot: %v", err) + } + if services.WorkflowSync == nil { + t.Fatal("workflow sync service is unavailable after PostgreSQL boot") + } + if _, err := services.WorkflowSync.GetConfigForWorkspace(context.Background(), "boot-workspace"); err != nil { + t.Fatalf("workflow sync persistence is unavailable after PostgreSQL boot: %v", err) + } + if services.Automation == nil || services.Automation.Service == nil { + t.Fatal("automation persistence is unavailable after PostgreSQL boot") + } if err := runInitialAgentSetup(context.Background(), services.User, agentSettingsController, log); err != nil { t.Fatalf("run initial agent setup with postgres: %v", err) } diff --git a/apps/backend/internal/db/dialect/dialect_test.go b/apps/backend/internal/db/dialect/dialect_test.go index fd37bba42f..da263b03f0 100644 --- a/apps/backend/internal/db/dialect/dialect_test.go +++ b/apps/backend/internal/db/dialect/dialect_test.go @@ -18,6 +18,15 @@ func TestIsPostgres(t *testing.T) { } } +func TestTimestampType(t *testing.T) { + if got := TimestampType(SQLite3); got != "DATETIME" { + t.Errorf("sqlite: got %q", got) + } + if got := TimestampType(PGX); got != "TIMESTAMPTZ" { + t.Errorf("pgx: got %q", got) + } +} + func TestBoolToInt(t *testing.T) { if BoolToInt(true) != 1 { t.Error("expected 1 for true") diff --git a/apps/backend/internal/db/dialect/types.go b/apps/backend/internal/db/dialect/types.go index b78c88c79c..6d8fae8af0 100644 --- a/apps/backend/internal/db/dialect/types.go +++ b/apps/backend/internal/db/dialect/types.go @@ -1,5 +1,14 @@ package dialect +// TimestampType returns the portable timestamp column type for the active +// driver. +func TimestampType(driver string) string { + if IsPostgres(driver) { + return "TIMESTAMPTZ" + } + return "DATETIME" +} + // BlobType returns the portable binary column type for the active driver. func BlobType(driver string) string { if IsPostgres(driver) { diff --git a/apps/backend/internal/db/schema.go b/apps/backend/internal/db/schema.go new file mode 100644 index 0000000000..8504146bed --- /dev/null +++ b/apps/backend/internal/db/schema.go @@ -0,0 +1,78 @@ +package db + +import "database/sql" + +// SchemaQuerier is the subset of sqlx database and transaction methods used +// by the portable schema probes. +type SchemaQuerier interface { + DriverName() string + Query(string, ...any) (*sql.Rows, error) + QueryRow(string, ...any) *sql.Row + Rebind(string) string +} + +// TableExists reports whether table exists in the active database schema. +// Missing tables are reported as false without an error. +func TableExists(conn SchemaQuerier, table string) (bool, error) { + query := `SELECT EXISTS ( + SELECT 1 FROM information_schema.tables + WHERE table_schema = current_schema() AND table_name = ? + )` + if !isPostgresSchema(conn) { + query = `SELECT EXISTS ( + SELECT 1 FROM sqlite_master + WHERE type = 'table' AND name = ? + )` + } + + var exists bool + if err := conn.QueryRow(conn.Rebind(query), table).Scan(&exists); err != nil { + return false, err + } + return exists, nil +} + +// TableColumns returns the column names declared by table. An absent table is +// reported as an empty map without an error. +func TableColumns(conn SchemaQuerier, table string) (map[string]bool, error) { + query := `SELECT column_name + FROM information_schema.columns + WHERE table_schema = current_schema() AND table_name = ? + ORDER BY ordinal_position` + if !isPostgresSchema(conn) { + query = `SELECT name FROM pragma_table_info(?) ORDER BY cid` + } + + rows, err := conn.Query(conn.Rebind(query), table) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + + columns := make(map[string]bool) + for rows.Next() { + var name string + if err := rows.Scan(&name); err != nil { + return nil, err + } + columns[name] = true + } + if err := rows.Err(); err != nil { + return nil, err + } + return columns, nil +} + +// ColumnExists reports whether table declares column. Missing tables and +// columns are reported as false without an error. +func ColumnExists(conn SchemaQuerier, table, column string) (bool, error) { + columns, err := TableColumns(conn, table) + if err != nil { + return false, err + } + return columns[column], nil +} + +func isPostgresSchema(conn SchemaQuerier) bool { + return conn.DriverName() == "pgx" +} diff --git a/apps/backend/internal/db/schema_postgres_test.go b/apps/backend/internal/db/schema_postgres_test.go new file mode 100644 index 0000000000..1c000d8fed --- /dev/null +++ b/apps/backend/internal/db/schema_postgres_test.go @@ -0,0 +1,57 @@ +package db + +import ( + "testing" + + "github.com/kandev/kandev/internal/testutil" +) + +func TestTableColumnsAndExistsPostgres(t *testing.T) { + database := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t)) + if _, err := database.Exec(`CREATE TABLE sample_schema ( + id TEXT PRIMARY KEY, + created_at TIMESTAMPTZ NOT NULL + )`); err != nil { + t.Fatalf("create table: %v", err) + } + + exists, err := TableExists(database, "sample_schema") + if err != nil { + t.Fatalf("table exists: %v", err) + } + if !exists { + t.Fatal("TableExists = false, want true") + } + + columns, err := TableColumns(database, "sample_schema") + if err != nil { + t.Fatalf("table columns: %v", err) + } + if !columns["created_at"] || columns["missing"] { + t.Fatalf("columns = %#v, want created_at and not missing", columns) + } + + got, err := ColumnExists(database, "sample_schema", "missing") + if err != nil { + t.Fatalf("missing column exists: %v", err) + } + if got { + t.Fatal("ColumnExists for missing column = true, want false") + } + + missingTable, err := TableExists(database, "missing_schema") + if err != nil { + t.Fatalf("missing table exists: %v", err) + } + if missingTable { + t.Fatal("TableExists for missing table = true, want false") + } + + missingColumns, err := TableColumns(database, "missing_schema") + if err != nil { + t.Fatalf("missing table columns: %v", err) + } + if len(missingColumns) != 0 { + t.Fatalf("missing table columns = %#v, want empty", missingColumns) + } +} diff --git a/apps/backend/internal/db/schema_test.go b/apps/backend/internal/db/schema_test.go new file mode 100644 index 0000000000..2f00abc525 --- /dev/null +++ b/apps/backend/internal/db/schema_test.go @@ -0,0 +1,72 @@ +package db + +import ( + "path/filepath" + "testing" + + "github.com/jmoiron/sqlx" +) + +func TestTableColumnsAndExistsSQLite(t *testing.T) { + rawDB, err := OpenSQLite(filepath.Join(t.TempDir(), "schema.db")) + if err != nil { + t.Fatalf("open sqlite: %v", err) + } + database := sqlx.NewDb(rawDB, "sqlite3") + t.Cleanup(func() { _ = database.Close() }) + + if _, err := database.Exec(`CREATE TABLE sample_schema ( + id TEXT PRIMARY KEY, + created_at DATETIME NOT NULL + )`); err != nil { + t.Fatalf("create table: %v", err) + } + + exists, err := TableExists(database, "sample_schema") + if err != nil { + t.Fatalf("table exists: %v", err) + } + if !exists { + t.Fatal("TableExists = false, want true") + } + + columns, err := TableColumns(database, "sample_schema") + if err != nil { + t.Fatalf("table columns: %v", err) + } + if !columns["created_at"] || columns["missing"] { + t.Fatalf("columns = %#v, want created_at and not missing", columns) + } + + for _, column := range []struct { + name string + want bool + }{ + {name: "id", want: true}, + {name: "missing", want: false}, + } { + got, err := ColumnExists(database, "sample_schema", column.name) + if err != nil { + t.Fatalf("column %s exists: %v", column.name, err) + } + if got != column.want { + t.Errorf("ColumnExists(%q) = %v, want %v", column.name, got, column.want) + } + } + + missingTable, err := TableExists(database, "missing_schema") + if err != nil { + t.Fatalf("missing table exists: %v", err) + } + if missingTable { + t.Fatal("TableExists for missing table = true, want false") + } + + missingColumns, err := TableColumns(database, "missing_schema") + if err != nil { + t.Fatalf("missing table columns: %v", err) + } + if len(missingColumns) != 0 { + t.Fatalf("missing table columns = %#v, want empty", missingColumns) + } +} diff --git a/apps/backend/internal/github/store.go b/apps/backend/internal/github/store.go index 233184096b..1b4f3f5e1b 100644 --- a/apps/backend/internal/github/store.go +++ b/apps/backend/internal/github/store.go @@ -15,6 +15,7 @@ import ( "github.com/jmoiron/sqlx" dbutil "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/db/dialect" "github.com/kandev/kandev/internal/persistence" ) @@ -45,10 +46,16 @@ func NewStore(writer, reader *sqlx.DB) (*Store, error) { db: writer, ro: reader, appLifecycleLocks: make(map[string]*appRegistrationLifecycleLock), } - s.freshInstall = !s.tableExists("github_workspace_settings") && - !s.tableExists("github_workspace_connections") - legacyUpgrade := s.tableExists("github_workspace_settings") && - !s.tableExists("github_workspace_connections") + settingsExists, err := dbutil.TableExists(s.db, "github_workspace_settings") + if err != nil { + return nil, fmt.Errorf("probe GitHub workspace settings schema: %w", err) + } + connectionsExists, err := dbutil.TableExists(s.db, "github_workspace_connections") + if err != nil { + return nil, fmt.Errorf("probe GitHub workspace connections schema: %w", err) + } + s.freshInstall = !settingsExists && !connectionsExists + legacyUpgrade := settingsExists && !connectionsExists if err := s.initSchema(legacyUpgrade); err != nil { return nil, fmt.Errorf("github schema init: %w", err) } @@ -555,25 +562,28 @@ func (s *Store) initSchemaFoundations() error { func (s *Store) applyIdempotentSchemaColumns() { // Idempotent migrations for existing databases. - _, _ = s.db.Exec(`ALTER TABLE github_pr_watches ADD COLUMN last_review_state TEXT DEFAULT ''`) - _, _ = s.db.Exec(`ALTER TABLE github_task_prs ADD COLUMN mergeable_state TEXT NOT NULL DEFAULT ''`) + exec := func(statement string) { + _, _ = s.db.Exec(schemaSQLForDriver(statement, s.db.DriverName())) + } + exec(`ALTER TABLE github_pr_watches ADD COLUMN last_review_state TEXT DEFAULT ''`) + exec(`ALTER TABLE github_task_prs ADD COLUMN mergeable_state TEXT NOT NULL DEFAULT ''`) // Phase 4 (multi-repo): per-repo PR association on github_task_prs. - _, _ = s.db.Exec(`ALTER TABLE github_task_prs ADD COLUMN repository_id TEXT NOT NULL DEFAULT ''`) - _, _ = s.db.Exec(`ALTER TABLE github_pr_watches ADD COLUMN repository_id TEXT NOT NULL DEFAULT ''`) + exec(`ALTER TABLE github_task_prs ADD COLUMN repository_id TEXT NOT NULL DEFAULT ''`) + exec(`ALTER TABLE github_pr_watches ADD COLUMN repository_id TEXT NOT NULL DEFAULT ''`) // CI popover: aggregate counts + branch protection's required_approving_review_count // + unresolved review-threads, surfaced in the PR top-bar hover popover so the // frontend can render the counts row without a second round-trip. - _, _ = s.db.Exec(`ALTER TABLE github_task_prs ADD COLUMN required_reviews INTEGER`) - _, _ = s.db.Exec(`ALTER TABLE github_task_prs ADD COLUMN unresolved_review_threads INTEGER DEFAULT 0`) - _, _ = s.db.Exec(`ALTER TABLE github_task_prs ADD COLUMN checks_total INTEGER DEFAULT 0`) - _, _ = s.db.Exec(`ALTER TABLE github_task_prs ADD COLUMN checks_passing INTEGER DEFAULT 0`) - _, _ = s.db.Exec(`ALTER TABLE github_task_prs ADD COLUMN detached_at DATETIME`) + exec(`ALTER TABLE github_task_prs ADD COLUMN required_reviews INTEGER`) + exec(`ALTER TABLE github_task_prs ADD COLUMN unresolved_review_threads INTEGER DEFAULT 0`) + exec(`ALTER TABLE github_task_prs ADD COLUMN checks_total INTEGER DEFAULT 0`) + exec(`ALTER TABLE github_task_prs ADD COLUMN checks_passing INTEGER DEFAULT 0`) + exec(`ALTER TABLE github_task_prs ADD COLUMN detached_at DATETIME`) // Per-watch cleanup policy for review/issue watches: controls whether the // poller deletes auto-created tasks when the underlying PR/issue reaches // a terminal state. Values: 'auto' (default — preserve only when user // engaged), 'always' (delete on terminal state), 'never' (manual only). - _, _ = s.db.Exec(`ALTER TABLE github_review_watches ADD COLUMN cleanup_policy TEXT NOT NULL DEFAULT 'auto'`) - _, _ = s.db.Exec(`ALTER TABLE github_issue_watches ADD COLUMN cleanup_policy TEXT NOT NULL DEFAULT 'auto'`) + exec(`ALTER TABLE github_review_watches ADD COLUMN cleanup_policy TEXT NOT NULL DEFAULT 'auto'`) + exec(`ALTER TABLE github_issue_watches ADD COLUMN cleanup_policy TEXT NOT NULL DEFAULT 'auto'`) } func (s *Store) initSchemaUpgrades() error { @@ -644,7 +654,10 @@ func (s *Store) addTaskPRMergeQueueColumns() error { if _, ok := columns[column.name]; ok { continue } - stmt := "ALTER TABLE github_task_prs ADD COLUMN " + column.name + " " + column.ddl + stmt := schemaSQLForDriver( + "ALTER TABLE github_task_prs ADD COLUMN "+column.name+" "+column.ddl, + s.db.DriverName(), + ) if _, err := s.db.Exec(stmt); err != nil && !dbutil.IsDuplicateColumnError(err) { return fmt.Errorf("add github_task_prs.%s: %w", column.name, err) } @@ -667,7 +680,9 @@ func (s *Store) addTaskPRSourceColumn() error { if _, ok := cols["source"]; ok { return nil } - if _, err := s.db.Exec(`ALTER TABLE github_task_prs ADD COLUMN source TEXT NOT NULL DEFAULT ''`); err != nil && + if _, err := s.db.Exec(schemaSQLForDriver( + `ALTER TABLE github_task_prs ADD COLUMN source TEXT NOT NULL DEFAULT ''`, s.db.DriverName(), + )); err != nil && !dbutil.IsDuplicateColumnError(err) { return fmt.Errorf("add github_task_prs.source: %w", err) } @@ -706,7 +721,10 @@ func (s *Store) addTaskPROutcomeColumns() error { if _, ok := cols[col.name]; ok { continue } - stmt := "ALTER TABLE github_task_prs ADD COLUMN " + col.name + " " + col.ddl + stmt := schemaSQLForDriver( + "ALTER TABLE github_task_prs ADD COLUMN "+col.name+" "+col.ddl, + s.db.DriverName(), + ) if _, err := s.db.Exec(stmt); err != nil && !dbutil.IsDuplicateColumnError(err) { return fmt.Errorf("add github_task_prs.%s: %w", col.name, err) } @@ -722,7 +740,10 @@ func (s *Store) addTaskGitCredentialsMode() error { if _, ok := columns["task_git_credentials_mode"]; ok { return nil } - if _, err := s.db.Exec(`ALTER TABLE github_workspace_settings ADD COLUMN task_git_credentials_mode TEXT NOT NULL DEFAULT 'managed'`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver( + `ALTER TABLE github_workspace_settings ADD COLUMN task_git_credentials_mode TEXT NOT NULL DEFAULT 'managed'`, + s.db.DriverName(), + )); err != nil { return fmt.Errorf("add github_workspace_settings.task_git_credentials_mode: %w", err) } return nil @@ -818,7 +839,7 @@ func (s *Store) fanOutTaskCIOptionsToPRScope( } defer func() { _ = tx.Rollback() }() now := time.Now().UTC() - if _, err := tx.Exec(` + if _, err := tx.Exec(tx.Rebind(` INSERT INTO github_task_pr_automation_options ( task_id, repository_id, pr_number, auto_fix_enabled, auto_merge_enabled, prompt_on_review_requested, prompt_on_merged, prompt_on_closed, created_at, updated_at @@ -826,12 +847,12 @@ func (s *Store) fanOutTaskCIOptionsToPRScope( SELECT task_id, repository_id, pr_number, ?, ?, ?, ?, ?, ?, ? FROM github_task_prs WHERE task_id = ? AND detached_at IS NULL - ON CONFLICT(task_id, repository_id, pr_number) DO NOTHING`, + ON CONFLICT(task_id, repository_id, pr_number) DO NOTHING`), autoFix, autoMerge, promptReview, promptMerged, promptClosed, now, now, taskID); err != nil { return fmt.Errorf("fan out task CI options for %s: %w", taskID, err) } if _, err := tx.Exec( - `UPDATE github_task_ci_options SET pr_scope_migrated_at = ? WHERE task_id = ?`, now, taskID, + tx.Rebind(`UPDATE github_task_ci_options SET pr_scope_migrated_at = ? WHERE task_id = ?`), now, taskID, ); err != nil { return fmt.Errorf("stamp pr_scope_migrated_at for %s: %w", taskID, err) } @@ -854,8 +875,14 @@ func (s *Store) applyIdempotentSchemaIndexes() { // pr_number is the 3rd column of UNIQUE(task_id, repository_id, pr_number), // so SQLite can't use that index for the PR-number task search. Add a // dedicated leading-key index so lookups by PR number stay index-backed. - _, _ = s.db.Exec(`CREATE INDEX IF NOT EXISTS idx_github_task_prs_pr_number ON github_task_prs (pr_number)`) - _, _ = s.db.Exec(`CREATE INDEX IF NOT EXISTS idx_github_task_ci_pr_state_task ON github_task_ci_pr_state (task_id)`) + _, _ = s.db.Exec(schemaSQLForDriver( + `CREATE INDEX IF NOT EXISTS idx_github_task_prs_pr_number ON github_task_prs (pr_number)`, + s.db.DriverName(), + )) + _, _ = s.db.Exec(schemaSQLForDriver( + `CREATE INDEX IF NOT EXISTS idx_github_task_ci_pr_state_task ON github_task_ci_pr_state (task_id)`, + s.db.DriverName(), + )) } func (s *Store) resetUnpublishedGitHubAuthSchema() error { @@ -898,6 +925,9 @@ func (s *Store) resetUnpublishedGitHubAuthSchema() error { } func (s *Store) unpublishedGitHubAuthSchemaNeedsReset() (bool, error) { + if dialect.IsPostgres(s.db.DriverName()) { + return false, nil + } for _, singleton := range []string{"github_app_registration", "github_app_registration_flow_head"} { if s.tableExists(singleton) { return true, nil @@ -944,7 +974,7 @@ func (s *Store) addAppRegistrationReferenceColumns() error { if _, exists := columns["app_registration_id"]; exists { continue } - if _, err := s.db.Exec(migration.statement); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(migration.statement, s.db.DriverName())); err != nil { return fmt.Errorf("add %s.app_registration_id: %w", migration.table, err) } } @@ -955,17 +985,114 @@ func (s *Store) initCoreSchema() error { if err := s.initAppRegistrationSchema(); err != nil { return err } - _, err := s.db.Exec(createTablesSQL) + _, err := s.db.Exec(schemaSQLForDriver(createTablesSQL, s.db.DriverName())) return err } func (s *Store) initAppRegistrationSchema() error { - if _, err := s.db.Exec(appRegistrationTablesSQL); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(appRegistrationTablesSQL, s.db.DriverName())); err != nil { return fmt.Errorf("initialize GitHub App registration schema: %w", err) } return nil } +func schemaSQLForDriver(schema, driver string) string { + timestampType := dialect.TimestampType(driver) + schema = strings.ReplaceAll(schema, "TIMESTAMP", timestampType) + schema = strings.ReplaceAll(schema, "DATETIME", timestampType) + if dialect.IsPostgres(driver) { + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 1", "BOOLEAN DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 0", "BOOLEAN DEFAULT FALSE") + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 1", "BOOLEAN NOT NULL DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 0", "BOOLEAN NOT NULL DEFAULT FALSE") + if strings.Contains(schema, "CREATE TRIGGER IF NOT EXISTS github_user_connections_registration_insert") { + schema = withoutSQLiteGitHubAuthTriggers(schema) + schema += postgresGitHubAuthTriggers() + } + } + return schema +} + +func withoutSQLiteGitHubAuthTriggers(schema string) string { + start := strings.Index(schema, "\n\tCREATE TRIGGER IF NOT EXISTS github_user_connections_registration_insert") + end := strings.Index(schema, "\n\tCREATE TABLE IF NOT EXISTS github_user_connection_versions") + if start < 0 || end <= start { + return schema + } + return schema[:start] + schema[end:] +} + +func postgresGitHubAuthTriggers() string { + return ` +CREATE OR REPLACE FUNCTION github_validate_user_connection_registration() +RETURNS trigger +LANGUAGE plpgsql +AS $kandev$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM github_workspace_connections workspace + WHERE workspace.workspace_id = NEW.workspace_id + AND workspace.source = 'github_app_installation' + AND workspace.app_registration_id = NEW.app_registration_id + ) THEN + RAISE EXCEPTION 'personal GitHub App registration must match workspace'; + END IF; + RETURN NEW; +END; +$kandev$; + +CREATE OR REPLACE FUNCTION github_validate_workspace_connection_registration() +RETURNS trigger +LANGUAGE plpgsql +AS $kandev$ +BEGIN + IF TG_OP = 'DELETE' THEN + IF EXISTS ( + SELECT 1 FROM github_user_connections personal + WHERE personal.workspace_id = OLD.workspace_id + ) THEN + RAISE EXCEPTION 'workspace GitHub App connection still has personal connections'; + END IF; + RETURN OLD; + END IF; + + IF EXISTS ( + SELECT 1 FROM github_user_connections personal + WHERE personal.workspace_id = OLD.workspace_id + AND ( + NEW.source <> 'github_app_installation' + OR NEW.app_registration_id IS NULL + OR personal.app_registration_id <> NEW.app_registration_id + ) + ) THEN + RAISE EXCEPTION 'workspace GitHub App registration must match personal connections'; + END IF; + RETURN NEW; +END; +$kandev$; + +DROP TRIGGER IF EXISTS github_user_connections_registration_insert ON github_user_connections; +CREATE TRIGGER github_user_connections_registration_insert +BEFORE INSERT ON github_user_connections +FOR EACH ROW EXECUTE FUNCTION github_validate_user_connection_registration(); + +DROP TRIGGER IF EXISTS github_user_connections_registration_update ON github_user_connections; +CREATE TRIGGER github_user_connections_registration_update +BEFORE UPDATE OF workspace_id, app_registration_id ON github_user_connections +FOR EACH ROW EXECUTE FUNCTION github_validate_user_connection_registration(); + +DROP TRIGGER IF EXISTS github_workspace_connections_registration_update ON github_workspace_connections; +CREATE TRIGGER github_workspace_connections_registration_update +BEFORE UPDATE OF source, app_registration_id ON github_workspace_connections +FOR EACH ROW EXECUTE FUNCTION github_validate_workspace_connection_registration(); + +DROP TRIGGER IF EXISTS github_workspace_connections_registration_delete ON github_workspace_connections; +CREATE TRIGGER github_workspace_connections_registration_delete +BEFORE DELETE ON github_workspace_connections +FOR EACH ROW EXECUTE FUNCTION github_validate_workspace_connection_registration(); +` +} + func (s *Store) backfillGitHubUserConnectionVersions() error { // Package-local tests may initialize the GitHub store before the shared // workspace schema. A database with existing user connections necessarily @@ -978,7 +1105,11 @@ func (s *Store) backfillGitHubUserConnectionVersions() error { SELECT workspace_id, user_id, credential_generation, updated_at FROM github_user_connections WHERE true ON CONFLICT(workspace_id, user_id) DO UPDATE SET - credential_generation = MAX(github_user_connection_versions.credential_generation, excluded.credential_generation), + credential_generation = CASE + WHEN github_user_connection_versions.credential_generation > excluded.credential_generation + THEN github_user_connection_versions.credential_generation + ELSE excluded.credential_generation + END, updated_at = excluded.updated_at`); err != nil { return fmt.Errorf("backfill GitHub user connection versions: %w", err) } @@ -1000,7 +1131,7 @@ func (s *Store) addGitHubAuthFlowExpectationColumns() error { if _, ok := columns[name]; ok { continue } - if _, err := s.db.Exec(statement); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(statement, s.db.DriverName())); err != nil { return fmt.Errorf("add github_auth_flows.%s: %w", name, err) } } @@ -1027,7 +1158,7 @@ func (s *Store) addWorkspaceOwnershipColumns() error { {"github_pr_watches", `ALTER TABLE github_pr_watches ADD COLUMN workspace_id TEXT NOT NULL DEFAULT ''`}, {"github_task_prs", `ALTER TABLE github_task_prs ADD COLUMN workspace_id TEXT NOT NULL DEFAULT ''`}, } { - if _, err := s.db.Exec(migration.stmt); err != nil && !dbutil.IsDuplicateColumnError(err) { + if _, err := s.db.Exec(schemaSQLForDriver(migration.stmt, s.db.DriverName())); err != nil && !dbutil.IsDuplicateColumnError(err) { return fmt.Errorf("add %s.workspace_id: %w", migration.table, err) } } @@ -1035,7 +1166,10 @@ func (s *Store) addWorkspaceOwnershipColumns() error { } func (s *Store) addReviewWatchTargetLogin() error { - _, err := s.db.Exec(`ALTER TABLE github_review_watches ADD COLUMN target_login TEXT NOT NULL DEFAULT ''`) + _, err := s.db.Exec(schemaSQLForDriver( + `ALTER TABLE github_review_watches ADD COLUMN target_login TEXT NOT NULL DEFAULT ''`, + s.db.DriverName(), + )) if err != nil && !dbutil.IsDuplicateColumnError(err) { return fmt.Errorf("add github_review_watches.target_login: %w", err) } @@ -1124,7 +1258,7 @@ func (s *Store) addTaskPRAgentAutomationColumns() error { if _, exists := columns[field.name]; exists { continue } - if _, err := s.db.Exec(field.sql); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(field.sql, s.db.DriverName())); err != nil { return fmt.Errorf("add %s.%s: %w", table, field.name, err) } } @@ -1133,12 +1267,12 @@ func (s *Store) addTaskPRAgentAutomationColumns() error { } func (s *Store) backfillTaskCIAutoMergeErrorKinds() error { - _, err := s.db.Exec(` + _, err := s.db.Exec(s.db.Rebind(` UPDATE github_task_ci_pr_state SET last_error_kind = ? WHERE last_error_kind = '' AND (last_error LIKE 'merge PR:%' - OR last_error LIKE 'PR status is not freshly synced for auto-merge%')`, + OR last_error LIKE 'PR status is not freshly synced for auto-merge%')`), TaskCIErrorKindAutoMerge) if err != nil { return fmt.Errorf("backfill CI auto-merge error kinds: %w", err) @@ -1279,7 +1413,9 @@ func (s *Store) addWatchSelfHealColumns() error { } } if _, ok := cols["last_error_at"]; !ok { - if _, err := s.db.Exec("ALTER TABLE " + table + " ADD COLUMN last_error_at DATETIME"); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver( + "ALTER TABLE "+table+" ADD COLUMN last_error_at DATETIME", s.db.DriverName(), + )); err != nil { return fmt.Errorf("add %s.last_error_at: %w", table, err) } } @@ -1298,7 +1434,9 @@ func (s *Store) addTaskCIRoundColumns() error { } } if _, ok := cols["auto_fix_exhausted_at"]; !ok { - if _, err := s.db.Exec("ALTER TABLE github_task_ci_pr_state ADD COLUMN auto_fix_exhausted_at DATETIME"); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver( + "ALTER TABLE github_task_ci_pr_state ADD COLUMN auto_fix_exhausted_at DATETIME", s.db.DriverName(), + )); err != nil { return fmt.Errorf("add github_task_ci_pr_state.auto_fix_exhausted_at: %w", err) } } @@ -1317,7 +1455,9 @@ func (s *Store) addPRScopeMigrationColumn() error { if _, ok := cols["pr_scope_migrated_at"]; ok { return nil } - if _, err := s.db.Exec(`ALTER TABLE github_task_ci_options ADD COLUMN pr_scope_migrated_at DATETIME`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver( + `ALTER TABLE github_task_ci_options ADD COLUMN pr_scope_migrated_at DATETIME`, s.db.DriverName(), + )); err != nil { return fmt.Errorf("add github_task_ci_options.pr_scope_migrated_at: %w", err) } return nil @@ -1328,36 +1468,23 @@ func (s *Store) addPRScopeMigrationColumn() error { // fresh install whose createTablesSQL already includes the columns. Mirrors // the helper in jira/store.go. func (s *Store) tableColumns(table string) (map[string]struct{}, error) { - rows, err := s.db.Query(fmt.Sprintf("PRAGMA table_info(%s)", table)) + columns, err := dbutil.TableColumns(s.db, table) if err != nil { return nil, err } - defer func() { _ = rows.Close() }() - cols := make(map[string]struct{}) - for rows.Next() { - var ( - cid int - name string - ctype string - notnull int - dflt sql.NullString - pk int - ) - if err := rows.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk); err != nil { - return nil, err - } - cols[name] = struct{}{} + result := make(map[string]struct{}, len(columns)) + for column := range columns { + result[column] = struct{}{} } - return cols, rows.Err() + return result, nil } -// tableExists returns true when the named table is present in sqlite_master. +// tableExists returns true when the named table is present in the active schema. // Used by the multi-repo backfill to skip cross-package healing in unit // tests that don't bring up the task schema. func (s *Store) tableExists(name string) bool { - var n int - err := s.db.QueryRow(`SELECT 1 FROM sqlite_master WHERE type='table' AND name=?`, name).Scan(&n) - return err == nil + exists, err := dbutil.TableExists(s.db, name) + return err == nil && exists } // migratePRTablesForMultiRepo rebuilds `github_pr_watches` and @@ -1371,6 +1498,9 @@ func (s *Store) tableExists(name string) bool { // single-repo shape, once for the interim multi-repo shape — so DBs caught // in either state upgrade cleanly to the multi-branch shape. func (s *Store) migratePRTablesForMultiRepo() error { + if dialect.IsPostgres(s.db.DriverName()) { + return nil + } for _, trigger := range []string{ "session_id TEXT NOT NULL UNIQUE", "UNIQUE(session_id, repository_id)\n", @@ -1496,6 +1626,9 @@ func (s *Store) migratePRTablesForMultiRepo() error { // transaction. No-op when the legacy substring is absent — fresh installs // already use the new schema and previously-migrated databases skip too. func (s *Store) rebuildIfHasLegacyConstraint(table, legacyConstraint, createNew, copyData string) error { + if dialect.IsPostgres(s.db.DriverName()) { + return nil + } var existingSQL string row := s.db.QueryRow(`SELECT sql FROM sqlite_master WHERE type='table' AND name=?`, table) if err := row.Scan(&existingSQL); err != nil { @@ -1537,9 +1670,9 @@ func (s *Store) CreatePRWatch(ctx context.Context, w *PRWatch) error { now := time.Now().UTC() w.CreatedAt = now w.UpdatedAt = now - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO github_pr_watches (id, workspace_id, session_id, task_id, repository_id, owner, repo, pr_number, branch, last_check_status, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`), w.ID, w.WorkspaceID, w.SessionID, w.TaskID, w.RepositoryID, w.Owner, w.Repo, w.PRNumber, w.Branch, w.LastCheckStatus, w.CreatedAt, w.UpdatedAt) return err } @@ -1550,7 +1683,7 @@ func (s *Store) CreatePRWatch(ctx context.Context, w *PRWatch) error { func (s *Store) GetPRWatchBySession(ctx context.Context, sessionID string) (*PRWatch, error) { var w PRWatch err := s.ro.GetContext(ctx, &w, - `SELECT * FROM github_pr_watches WHERE session_id = ? LIMIT 1`, sessionID) + s.ro.Rebind(`SELECT * FROM github_pr_watches WHERE session_id = ? LIMIT 1`), sessionID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -1560,7 +1693,7 @@ func (s *Store) GetPRWatchBySession(ctx context.Context, sessionID string) (*PRW // GetPRWatch returns a PR watch by ID. func (s *Store) GetPRWatch(ctx context.Context, id string) (*PRWatch, error) { var w PRWatch - err := s.ro.GetContext(ctx, &w, `SELECT * FROM github_pr_watches WHERE id = ?`, id) + err := s.ro.GetContext(ctx, &w, s.ro.Rebind(`SELECT * FROM github_pr_watches WHERE id = ?`), id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -1578,9 +1711,9 @@ func (s *Store) GetPRWatch(ctx context.Context, id string) (*PRWatch, error) { func (s *Store) GetPRWatchBySessionAndRepo(ctx context.Context, sessionID, repositoryID string) (*PRWatch, error) { var w PRWatch err := s.ro.GetContext(ctx, &w, - `SELECT * FROM github_pr_watches WHERE session_id = ? AND repository_id = ? + s.ro.Rebind(`SELECT * FROM github_pr_watches WHERE session_id = ? AND repository_id = ? ORDER BY updated_at DESC LIMIT 1`, - sessionID, repositoryID) + ), sessionID, repositoryID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -1595,9 +1728,9 @@ func (s *Store) GetPRWatchBySessionAndRepo(ctx context.Context, sessionID, repos func (s *Store) GetPRWatchBySessionRepoAndBranch(ctx context.Context, sessionID, repositoryID, branch string) (*PRWatch, error) { var w PRWatch err := s.ro.GetContext(ctx, &w, - `SELECT * FROM github_pr_watches + s.ro.Rebind(`SELECT * FROM github_pr_watches WHERE session_id = ? AND repository_id = ? AND branch = ? LIMIT 1`, - sessionID, repositoryID, branch) + ), sessionID, repositoryID, branch) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -1609,7 +1742,7 @@ func (s *Store) GetPRWatchBySessionRepoAndBranch(ctx context.Context, sessionID, func (s *Store) ListPRWatchesBySession(ctx context.Context, sessionID string) ([]*PRWatch, error) { var watches []*PRWatch err := s.ro.SelectContext(ctx, &watches, - `SELECT * FROM github_pr_watches WHERE session_id = ? ORDER BY created_at ASC`, sessionID) + s.ro.Rebind(`SELECT * FROM github_pr_watches WHERE session_id = ? ORDER BY created_at ASC`), sessionID) return watches, err } @@ -1618,7 +1751,7 @@ func (s *Store) ListPRWatchesBySession(ctx context.Context, sessionID string) ([ // ListPRWatchesByTask when every repo's watch is needed. func (s *Store) GetPRWatchByTask(ctx context.Context, taskID string) (*PRWatch, error) { var w PRWatch - err := s.ro.GetContext(ctx, &w, `SELECT * FROM github_pr_watches WHERE task_id = ? ORDER BY updated_at DESC LIMIT 1`, taskID) + err := s.ro.GetContext(ctx, &w, s.ro.Rebind(`SELECT * FROM github_pr_watches WHERE task_id = ? ORDER BY updated_at DESC LIMIT 1`), taskID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -1630,7 +1763,7 @@ func (s *Store) GetPRWatchByTask(ctx context.Context, taskID string) (*PRWatch, func (s *Store) ListPRWatchesByTask(ctx context.Context, taskID string) ([]*PRWatch, error) { var watches []*PRWatch err := s.ro.SelectContext(ctx, &watches, - `SELECT * FROM github_pr_watches WHERE task_id = ? ORDER BY created_at ASC`, taskID) + s.ro.Rebind(`SELECT * FROM github_pr_watches WHERE task_id = ? ORDER BY created_at ASC`), taskID) return watches, err } @@ -1640,44 +1773,44 @@ func (s *Store) ListPRWatchesByTask(ctx context.Context, taskID string) ([]*PRWa // on `tasks` is used so orphans are dropped automatically. func (s *Store) ListActivePRWatches(ctx context.Context) ([]*PRWatch, error) { var watches []*PRWatch - err := s.ro.SelectContext(ctx, &watches, ` + err := s.ro.SelectContext(ctx, &watches, s.ro.Rebind(` SELECT w.* FROM github_pr_watches w INNER JOIN tasks t ON t.id = w.task_id WHERE t.archived_at IS NULL - ORDER BY w.created_at`) + ORDER BY w.created_at`)) return watches, err } // ListActivePRWatchesForWorkspace returns active watches only for one workspace. func (s *Store) ListActivePRWatchesForWorkspace(ctx context.Context, workspaceID string) ([]*PRWatch, error) { var watches []*PRWatch - err := s.ro.SelectContext(ctx, &watches, ` + err := s.ro.SelectContext(ctx, &watches, s.ro.Rebind(` SELECT w.* FROM github_pr_watches w INNER JOIN tasks t ON t.id = w.task_id WHERE w.workspace_id = ? AND t.archived_at IS NULL - ORDER BY w.created_at`, workspaceID) + ORDER BY w.created_at`), workspaceID) return watches, err } // UpdatePRWatchTimestamps updates the last checked timestamps and status fields. func (s *Store) UpdatePRWatchTimestamps(ctx context.Context, id string, checkedAt time.Time, commentAt *time.Time, checkStatus, reviewState string) error { - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE github_pr_watches SET last_checked_at = ?, last_comment_at = ?, last_check_status = ?, last_review_state = ?, updated_at = ? - WHERE id = ?`, + WHERE id = ?`), checkedAt, commentAt, checkStatus, reviewState, time.Now().UTC(), id) return err } // DeletePRWatch deletes a PR watch by ID. func (s *Store) DeletePRWatch(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM github_pr_watches WHERE id = ?`, id) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM github_pr_watches WHERE id = ?`), id) return err } // DeletePRWatchesByTaskID deletes all PR watches for a task. Returns the number // of rows removed so callers can log meaningful diagnostics. func (s *Store) DeletePRWatchesByTaskID(ctx context.Context, taskID string) (int64, error) { - res, err := s.db.ExecContext(ctx, `DELETE FROM github_pr_watches WHERE task_id = ?`, taskID) + res, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM github_pr_watches WHERE task_id = ?`), taskID) if err != nil { return 0, err } @@ -1690,8 +1823,8 @@ func (s *Store) DeletePRWatchesByTaskID(ctx context.Context, taskID string) (int // UpdatePRWatchPRNumber updates a PR watch's PR number after discovery. func (s *Store) UpdatePRWatchPRNumber(ctx context.Context, id string, prNumber int) error { - _, err := s.db.ExecContext(ctx, - `UPDATE github_pr_watches SET pr_number = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE github_pr_watches SET pr_number = ?, updated_at = ? WHERE id = ?`), prNumber, time.Now().UTC(), id) return err } @@ -1700,8 +1833,8 @@ func (s *Store) UpdatePRWatchPRNumber(ctx context.Context, id string, prNumber i // discovery. A watch can start on a contributor fork while the PR targets the // canonical parent repository. func (s *Store) UpdatePRWatchRepository(ctx context.Context, id, owner, repo string) error { - _, err := s.db.ExecContext(ctx, - `UPDATE github_pr_watches SET owner = ?, repo = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE github_pr_watches SET owner = ?, repo = ?, updated_at = ? WHERE id = ?`), owner, repo, time.Now().UTC(), id) return err } @@ -1712,8 +1845,8 @@ func (s *Store) UpdatePRWatchRepository(ctx context.Context, id, owner, repo str // for a PR on the new branch without leaving an inconsistent intermediate // state. func (s *Store) ResetPRWatch(ctx context.Context, id, branch string) error { - _, err := s.db.ExecContext(ctx, - `UPDATE github_pr_watches SET branch = ?, pr_number = 0, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE github_pr_watches SET branch = ?, pr_number = 0, updated_at = ? WHERE id = ?`), branch, time.Now().UTC(), id) return err } @@ -1728,7 +1861,7 @@ func (s *Store) ResetPRWatch(ctx context.Context, id, branch string) error { // source row (which is still searching, pr_number=0, so it owns no PR // state) and let the sibling continue to track the branch. func (s *Store) UpdatePRWatchBranchIfSearching(ctx context.Context, id, branch string) error { - tx, err := s.db.BeginTx(ctx, nil) + tx, err := s.db.BeginTxx(ctx, nil) if err != nil { return err } @@ -1736,8 +1869,8 @@ func (s *Store) UpdatePRWatchBranchIfSearching(ctx context.Context, id, branch s var sessionID, repositoryID string var prNumber int - err = tx.QueryRowContext(ctx, - `SELECT session_id, repository_id, pr_number FROM github_pr_watches WHERE id = ?`, id). + err = tx.QueryRowxContext(ctx, tx.Rebind( + `SELECT session_id, repository_id, pr_number FROM github_pr_watches WHERE id = ?`), id). Scan(&sessionID, &repositoryID, &prNumber) if errors.Is(err, sql.ErrNoRows) { return tx.Commit() @@ -1750,10 +1883,10 @@ func (s *Store) UpdatePRWatchBranchIfSearching(ctx context.Context, id, branch s } var probe int // existence probe only; value unused - err = tx.QueryRowContext(ctx, + err = tx.QueryRowxContext(ctx, tx.Rebind( `SELECT 1 FROM github_pr_watches WHERE session_id = ? AND repository_id = ? AND branch = ? AND id <> ?`, - sessionID, repositoryID, branch, id).Scan(&probe) + ), sessionID, repositoryID, branch, id).Scan(&probe) if err != nil && !errors.Is(err, sql.ErrNoRows) { return err } @@ -1761,8 +1894,8 @@ func (s *Store) UpdatePRWatchBranchIfSearching(ctx context.Context, id, branch s return dropSourceAndCommit(ctx, tx, id) } - if _, err := tx.ExecContext(ctx, - `UPDATE github_pr_watches SET branch = ?, updated_at = ? WHERE id = ? AND pr_number = 0`, + if _, err := tx.ExecContext(ctx, tx.Rebind( + `UPDATE github_pr_watches SET branch = ?, updated_at = ? WHERE id = ? AND pr_number = 0`), branch, time.Now().UTC(), id); err != nil { // Defensive belt-and-suspenders: the SQLite writer pool is // SetMaxOpenConns(1), so an in-process CreatePRWatch cannot @@ -1770,7 +1903,7 @@ func (s *Store) UpdatePRWatchBranchIfSearching(ctx context.Context, id, branch s // an external writer (separate process touching the same file, // future pool reshuffle) could; if the UPDATE still trips // UNIQUE, treat it identically to the probe-found path. - if strings.Contains(err.Error(), "UNIQUE constraint failed") { + if strings.Contains(err.Error(), "UNIQUE constraint failed") || strings.Contains(err.Error(), "duplicate key") { return dropSourceAndCommit(ctx, tx, id) } return err @@ -1780,9 +1913,9 @@ func (s *Store) UpdatePRWatchBranchIfSearching(ctx context.Context, id, branch s // dropSourceAndCommit removes a still-searching source watch (pr_number=0) // whose destination branch is already owned by a sibling row, then commits. -func dropSourceAndCommit(ctx context.Context, tx *sql.Tx, id string) error { - if _, err := tx.ExecContext(ctx, - `DELETE FROM github_pr_watches WHERE id = ? AND pr_number = 0`, id); err != nil { +func dropSourceAndCommit(ctx context.Context, tx *sqlx.Tx, id string) error { + if _, err := tx.ExecContext(ctx, tx.Rebind( + `DELETE FROM github_pr_watches WHERE id = ? AND pr_number = 0`), id); err != nil { return err } return tx.Commit() @@ -1836,6 +1969,7 @@ const taskPRColumnsQualified = `gtp.id, gtp.workspace_id, gtp.task_id, gtp.repos type taskPRWriter interface { ExecContext(context.Context, string, ...any) (sql.Result, error) + Rebind(string) string } func insertTaskPR(ctx context.Context, writer taskPRWriter, tp *TaskPR) error { @@ -1845,8 +1979,8 @@ func insertTaskPR(ctx context.Context, writer taskPRWriter, tp *TaskPR) error { return fmt.Errorf("task PR insert arity mismatch: %d columns, %d values", columnCount, len(values)) } placeholders := strings.TrimSuffix(strings.Repeat("?,", columnCount), ",") - _, err := writer.ExecContext(ctx, - `INSERT INTO github_task_prs (`+taskPRColumns+`) VALUES (`+placeholders+`)`, + _, err := writer.ExecContext(ctx, writer.Rebind( + `INSERT INTO github_task_prs (`+taskPRColumns+`) VALUES (`+placeholders+`)`), values..., ) return err @@ -1882,7 +2016,8 @@ func taskPRValues(tp *TaskPR) []any { // the result is non-deterministic across repos — use ListTaskPRsByTask instead. func (s *Store) GetTaskPR(ctx context.Context, taskID string) (*TaskPR, error) { var tp TaskPR - err := s.ro.GetContext(ctx, &tp, `SELECT `+taskPRColumns+` FROM github_task_prs WHERE task_id = ? AND detached_at IS NULL LIMIT 1`, taskID) + err := s.ro.GetContext(ctx, &tp, s.ro.Rebind( + `SELECT `+taskPRColumns+` FROM github_task_prs WHERE task_id = ? AND detached_at IS NULL LIMIT 1`), taskID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -1895,7 +2030,7 @@ func (s *Store) GetTaskPR(ctx context.Context, taskID string) (*TaskPR, error) { func (s *Store) GetTaskPRByID(ctx context.Context, associationID string) (*TaskPR, error) { var tp TaskPR err := s.ro.GetContext(ctx, &tp, - `SELECT `+taskPRColumns+` FROM github_task_prs WHERE id = ? LIMIT 1`, associationID) + s.ro.Rebind(`SELECT `+taskPRColumns+` FROM github_task_prs WHERE id = ? LIMIT 1`), associationID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -1912,8 +2047,8 @@ func (s *Store) GetTaskPRByID(ctx context.Context, associationID string) (*TaskP func (s *Store) GetTaskPRByRepository(ctx context.Context, taskID, repositoryID string) (*TaskPR, error) { var tp TaskPR err := s.ro.GetContext(ctx, &tp, - `SELECT `+taskPRColumns+` FROM github_task_prs WHERE task_id = ? AND repository_id = ? AND detached_at IS NULL - ORDER BY updated_at DESC LIMIT 1`, + s.ro.Rebind(`SELECT `+taskPRColumns+` FROM github_task_prs WHERE task_id = ? AND repository_id = ? AND detached_at IS NULL + ORDER BY updated_at DESC LIMIT 1`), taskID, repositoryID) if errors.Is(err, sql.ErrNoRows) { return nil, nil @@ -1929,8 +2064,8 @@ func (s *Store) GetTaskPRByRepository(ctx context.Context, taskID, repositoryID func (s *Store) GetTaskPRByRepoAndNumber(ctx context.Context, taskID, repositoryID string, prNumber int) (*TaskPR, error) { var tp TaskPR err := s.ro.GetContext(ctx, &tp, - `SELECT `+taskPRColumns+` FROM github_task_prs - WHERE task_id = ? AND repository_id = ? AND pr_number = ? AND detached_at IS NULL LIMIT 1`, + s.ro.Rebind(`SELECT `+taskPRColumns+` FROM github_task_prs + WHERE task_id = ? AND repository_id = ? AND pr_number = ? AND detached_at IS NULL LIMIT 1`), taskID, repositoryID, prNumber) if errors.Is(err, sql.ErrNoRows) { return nil, nil @@ -1944,8 +2079,8 @@ func (s *Store) GetTaskPRByRepoAndNumber(ctx context.Context, taskID, repository func (s *Store) GetTaskPRByRepoAndNumberIncludingDetached(ctx context.Context, taskID, repositoryID string, prNumber int) (*TaskPR, error) { var tp TaskPR err := s.ro.GetContext(ctx, &tp, - `SELECT `+taskPRColumns+` FROM github_task_prs - WHERE task_id = ? AND repository_id = ? AND pr_number = ? LIMIT 1`, + s.ro.Rebind(`SELECT `+taskPRColumns+` FROM github_task_prs + WHERE task_id = ? AND repository_id = ? AND pr_number = ? LIMIT 1`), taskID, repositoryID, prNumber) if errors.Is(err, sql.ErrNoRows) { return nil, nil @@ -1958,7 +2093,7 @@ func (s *Store) GetTaskPRByRepoAndNumberIncludingDetached(ctx context.Context, t func (s *Store) ListTaskPRsByTask(ctx context.Context, taskID string) ([]*TaskPR, error) { var prs []TaskPR if err := s.ro.SelectContext(ctx, &prs, - `SELECT `+taskPRColumns+` FROM github_task_prs WHERE task_id = ? AND detached_at IS NULL ORDER BY created_at ASC`, taskID); err != nil { + s.ro.Rebind(`SELECT `+taskPRColumns+` FROM github_task_prs WHERE task_id = ? AND detached_at IS NULL ORDER BY created_at ASC`), taskID); err != nil { return nil, err } out := make([]*TaskPR, 0, len(prs)) @@ -1975,7 +2110,7 @@ func (s *Store) ListTaskPRsByTask(ctx context.Context, taskID string) ([]*TaskPR func (s *Store) ListTaskPRsByTaskIncludingDetached(ctx context.Context, taskID string) ([]*TaskPR, error) { var prs []TaskPR if err := s.ro.SelectContext(ctx, &prs, - `SELECT `+taskPRColumns+` FROM github_task_prs WHERE task_id = ? ORDER BY created_at ASC`, taskID); err != nil { + s.ro.Rebind(`SELECT `+taskPRColumns+` FROM github_task_prs WHERE task_id = ? ORDER BY created_at ASC`), taskID); err != nil { return nil, err } out := make([]*TaskPR, 0, len(prs)) @@ -1990,9 +2125,9 @@ func (s *Store) ListTaskPRsByTaskIncludingDetached(ctx context.Context, taskID s // The bool return reports whether this call performed the transition. func (s *Store) DetachTaskPR(ctx context.Context, associationID string) (*TaskPR, bool, error) { now := time.Now().UTC() - result, err := s.db.ExecContext(ctx, + result, err := s.db.ExecContext(ctx, s.db.Rebind( `UPDATE github_task_prs SET detached_at = ?, updated_at = ? - WHERE id = ? AND detached_at IS NULL`, now, now, associationID) + WHERE id = ? AND detached_at IS NULL`), now, now, associationID) if err != nil { return nil, false, err } @@ -2028,8 +2163,8 @@ func (s *Store) RestoreTaskPR(ctx context.Context, taskID, repositoryID string, var outgoing TaskPR err = tx.GetContext(ctx, &outgoing, - `SELECT `+taskPRColumns+` FROM github_task_prs - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, + tx.Rebind(`SELECT `+taskPRColumns+` FROM github_task_prs + WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), taskID, repositoryID, pr.Number) if err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, err @@ -2043,7 +2178,7 @@ func (s *Store) RestoreTaskPR(ctx context.Context, taskID, repositoryID string, headSHA = pr.HeadSHA } - if _, err := tx.ExecContext(ctx, + if _, err := tx.ExecContext(ctx, tx.Rebind( `UPDATE github_task_prs SET owner = ?, repo = ?, pr_url = ?, pr_title = ?, head_branch = ?, base_branch = ?, head_sha = ?, author_login = ?, state = ?, mergeable_state = ?, merge_queue_state = ?, merge_queue_position = ?, merge_queue_entry_id = ?, merge_queue_entry_head_sha = ?, merge_queue_estimated_time_to_merge_seconds = ?, @@ -2051,7 +2186,7 @@ func (s *Store) RestoreTaskPR(ctx context.Context, taskID, repositoryID string, additions = ?, deletions = ?, merged_at = ?, closed_at = ?, detached_at = NULL, updated_at = ?, is_draft = ?, changed_files = ?, merged_by_login = ?, closed_by_login = ?, auto_merge_observed_at = COALESCE(auto_merge_observed_at, ?) - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, + WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), pr.RepoOwner, pr.RepoName, pr.HTMLURL, pr.Title, pr.HeadBranch, pr.BaseBranch, headSHA, pr.AuthorLogin, pr.State, pr.MergeableState, queue.state, queue.position, queue.entryID, queue.entryHeadSHA, queue.estimate, queue.lastRemovalID, queue.lastRemovedAt, queue.lastRemovalReason, queue.lastRemovalBeforeSHA, @@ -2094,10 +2229,10 @@ func (s *Store) ListTaskPRsByTaskIDs(ctx context.Context, taskIDs []string) (map func (s *Store) ListTaskPRsByWorkspaceID(ctx context.Context, workspaceID string) (map[string][]*TaskPR, error) { var prs []TaskPR if err := s.ro.SelectContext(ctx, &prs, - `SELECT `+taskPRColumnsQualified+` FROM github_task_prs gtp + s.ro.Rebind(`SELECT `+taskPRColumnsQualified+` FROM github_task_prs gtp INNER JOIN tasks t ON gtp.task_id = t.id WHERE t.workspace_id = ? AND gtp.detached_at IS NULL - ORDER BY gtp.created_at ASC`, workspaceID); err != nil { + ORDER BY gtp.created_at ASC`), workspaceID); err != nil { return nil, err } return groupTaskPRsByTask(prs), nil @@ -2124,9 +2259,9 @@ func (s *Store) ListTaskIssueMetadataByWorkspaceID(ctx context.Context, workspac func (s *Store) ListTaskIDsByPRNumber(ctx context.Context, workspaceID string, prNumber int) ([]string, error) { var ids []string if err := s.ro.SelectContext(ctx, &ids, - `SELECT DISTINCT gtp.task_id FROM github_task_prs gtp + s.ro.Rebind(`SELECT DISTINCT gtp.task_id FROM github_task_prs gtp INNER JOIN tasks t ON gtp.task_id = t.id - WHERE t.workspace_id = ? AND gtp.pr_number = ? AND gtp.detached_at IS NULL`, workspaceID, prNumber); err != nil { + WHERE t.workspace_id = ? AND gtp.pr_number = ? AND gtp.detached_at IS NULL`), workspaceID, prNumber); err != nil { return nil, err } return ids, nil @@ -2143,11 +2278,11 @@ func (s *Store) ListTaskPRsByPRNumber( ) ([]*TaskPR, error) { var prs []TaskPR if err := s.ro.SelectContext(ctx, &prs, - `SELECT `+taskPRColumnsQualified+` FROM github_task_prs gtp + s.ro.Rebind(`SELECT `+taskPRColumnsQualified+` FROM github_task_prs gtp INNER JOIN tasks t ON gtp.task_id = t.id WHERE t.workspace_id = ? AND gtp.owner = ? AND gtp.repo = ? AND gtp.pr_number = ? AND gtp.detached_at IS NULL - ORDER BY gtp.created_at ASC`, workspaceID, owner, repo, prNumber); err != nil { + ORDER BY gtp.created_at ASC`), workspaceID, owner, repo, prNumber); err != nil { return nil, err } out := make([]*TaskPR, 0, len(prs)) @@ -2224,16 +2359,16 @@ func (s *Store) ReplaceTaskPR(ctx context.Context, tp *TaskPR, status *PRStatus) } if tp.RepositoryID != "" { - if _, err := tx.ExecContext(ctx, + if _, err := tx.ExecContext(ctx, tx.Rebind( `DELETE FROM github_task_prs - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, + WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), tp.TaskID, tp.RepositoryID, tp.PRNumber); err != nil { return nil, err } } else { - if _, err := tx.ExecContext(ctx, + if _, err := tx.ExecContext(ctx, tx.Rebind( `DELETE FROM github_task_prs - WHERE task_id = ? AND repository_id = '' AND pr_number = ?`, + WHERE task_id = ? AND repository_id = '' AND pr_number = ?`), tp.TaskID, tp.PRNumber); err != nil { return nil, err } @@ -2257,13 +2392,13 @@ func replaceTaskPROutgoingRow(ctx context.Context, tx *sqlx.Tx, tp *TaskPR) (*Ta var err error if tp.RepositoryID != "" { err = tx.GetContext(ctx, &outgoing, - `SELECT `+taskPRColumns+` FROM github_task_prs - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, + tx.Rebind(`SELECT `+taskPRColumns+` FROM github_task_prs + WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), tp.TaskID, tp.RepositoryID, tp.PRNumber) } else { err = tx.GetContext(ctx, &outgoing, - `SELECT `+taskPRColumns+` FROM github_task_prs - WHERE task_id = ? AND repository_id = '' AND pr_number = ?`, + tx.Rebind(`SELECT `+taskPRColumns+` FROM github_task_prs + WHERE task_id = ? AND repository_id = '' AND pr_number = ?`), tp.TaskID, tp.PRNumber) } if errors.Is(err, sql.ErrNoRows) { @@ -2290,12 +2425,13 @@ func replaceTaskPROutgoingRow(ctx context.Context, tx *sqlx.Tx, tp *TaskPR) (*Ta // is silently discarded instead of overwriting it (AC-16/AC-17). func (s *Store) UpdateTaskPR(ctx context.Context, tp *TaskPR) error { tp.UpdatedAt = time.Now().UTC() + removalAfter := dialect.DurationMs(s.db.DriverName(), "?", "merge_queue_last_removed_at") tx, err := s.db.BeginTxx(ctx, nil) if err != nil { return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_prs SET state = ?, review_state = ?, checks_state = ?, mergeable_state = ?, head_sha = ?, merge_queue_state = ?, merge_queue_position = ?, merge_queue_entry_id = ?, merge_queue_entry_head_sha = ?, merge_queue_estimated_time_to_merge_seconds = ?, review_count = ?, pending_review_count = ?, required_reviews = ?, comment_count = ?, @@ -2304,7 +2440,7 @@ func (s *Store) UpdateTaskPR(ctx context.Context, tp *TaskPR) error { merged_at = ?, closed_at = ?, last_synced_at = ?, updated_at = ?, is_draft = ?, changed_files = ?, merged_by_login = ?, closed_by_login = ?, auto_merge_observed_at = COALESCE(auto_merge_observed_at, ?) - WHERE id = ?`, + WHERE id = ?`), tp.State, tp.ReviewState, tp.ChecksState, tp.MergeableState, tp.HeadSHA, tp.MergeQueueState, tp.MergeQueuePosition, tp.MergeQueueEntryID, tp.MergeQueueEntryHeadSHA, tp.MergeQueueEstimatedTimeToMergeSeconds, tp.ReviewCount, tp.PendingReviewCount, tp.RequiredReviews, tp.CommentCount, tp.UnresolvedReviewThreads, tp.ChecksTotal, tp.ChecksPassing, @@ -2314,7 +2450,7 @@ func (s *Store) UpdateTaskPR(ctx context.Context, tp *TaskPR) error { tp.AutoMergeObservedAt, tp.ID); err != nil { return err } - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_prs SET merge_queue_last_removal_id = ?, merge_queue_last_removed_at = ?, merge_queue_last_removal_reason = ?, merge_queue_last_removal_before_sha = ? @@ -2324,8 +2460,8 @@ func (s *Store) UpdateTaskPR(ctx context.Context, tp *TaskPR) error { AND ( merge_queue_last_removal_id = '' OR merge_queue_last_removed_at IS NULL - OR julianday(?) > julianday(merge_queue_last_removed_at) - )`, + OR `+removalAfter+` > 0 + )`), tp.MergeQueueLastRemovalID, tp.MergeQueueLastRemovedAt, tp.MergeQueueLastRemovalReason, tp.MergeQueueLastRemovalBeforeSHA, tp.ID, tp.MergeQueueLastRemovalID, tp.MergeQueueLastRemovalID, tp.MergeQueueLastRemovedAt); err != nil { @@ -2339,7 +2475,8 @@ func (s *Store) UpdateTaskPR(ctx context.Context, tp *TaskPR) error { // GetTaskCIOptions returns persisted task CI automation options, or disabled defaults. func (s *Store) GetTaskCIOptions(ctx context.Context, taskID string) (*TaskCIOptions, error) { var opts TaskCIOptions - err := s.ro.GetContext(ctx, &opts, `SELECT * FROM github_task_ci_options WHERE task_id = ?`, taskID) + err := s.ro.GetContext(ctx, &opts, + s.ro.Rebind(`SELECT * FROM github_task_ci_options WHERE task_id = ?`), taskID) if errors.Is(err, sql.ErrNoRows) { now := time.Now().UTC() return &TaskCIOptions{TaskID: taskID, CreatedAt: now, UpdatedAt: now}, nil @@ -2358,12 +2495,13 @@ func (s *Store) advanceTaskCIOptionsVersion( ) (time.Time, error) { candidate = candidate.UTC() var current time.Time - err := tx.GetContext(ctx, ¤t, `SELECT updated_at FROM github_task_ci_options WHERE task_id = ?`, taskID) + err := tx.GetContext(ctx, ¤t, + tx.Rebind(`SELECT updated_at FROM github_task_ci_options WHERE task_id = ?`), taskID) if errors.Is(err, sql.ErrNoRows) { - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO github_task_ci_options ( - task_id, auto_fix_enabled, auto_merge_enabled, auto_fix_prompt_override, created_at, updated_at - ) VALUES (?, 0, 0, NULL, ?, ?)`, + task_id, auto_fix_prompt_override, created_at, updated_at + ) VALUES (?, NULL, ?, ?)`), taskID, candidate, candidate); err != nil { return time.Time{}, err } @@ -2377,8 +2515,8 @@ func (s *Store) advanceTaskCIOptionsVersion( if !version.After(current) { version = current.Add(time.Nanosecond) } - if _, err := tx.ExecContext(ctx, - `UPDATE github_task_ci_options SET updated_at = ? WHERE task_id = ?`, version, taskID); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind( + `UPDATE github_task_ci_options SET updated_at = ? WHERE task_id = ?`), version, taskID); err != nil { return time.Time{}, err } return version, nil @@ -2469,7 +2607,8 @@ func (s *Store) updateTaskCIOptionsTx( return err } var previous TaskCIOptions - if err := tx.GetContext(ctx, &previous, `SELECT * FROM github_task_ci_options WHERE task_id = ?`, taskID); err != nil { + if err := tx.GetContext(ctx, &previous, + tx.Rebind(`SELECT * FROM github_task_ci_options WHERE task_id = ?`), taskID); err != nil { return err } autoFixSet, autoFixValue := boolPatchValue(patch.AutoFixEnabled) @@ -2483,7 +2622,7 @@ func (s *Store) updateTaskCIOptionsTx( reviewerChanged := reviewerLoginSet && !strings.EqualFold( previous.ReviewReviewerLogin, normalizedString(patch.ReviewReviewerLogin), ) - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_ci_options SET auto_fix_enabled = CASE WHEN ? THEN ? ELSE auto_fix_enabled END, auto_merge_enabled = CASE WHEN ? THEN ? ELSE auto_merge_enabled END, @@ -2493,7 +2632,7 @@ func (s *Store) updateTaskCIOptionsTx( prompt_on_closed = CASE WHEN ? THEN ? ELSE prompt_on_closed END, review_reviewer_login = CASE WHEN ? THEN ? ELSE review_reviewer_login END, updated_at = ? - WHERE task_id = ?`, + WHERE task_id = ?`), autoFixSet, autoFixValue, autoMergeSet, autoMergeValue, promptSet, promptValue, reviewSet, reviewValue, mergedSet, mergedValue, closedSet, closedValue, reviewerLoginSet, normalizedString(patch.ReviewReviewerLogin), @@ -2520,10 +2659,10 @@ func applyTaskCIOptionResets( if shouldResetReviewRequests( patch.PromptOnReviewRequested, previous.PromptOnReviewRequested, reviewerChanged, ) { - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_ci_pr_state - SET review_request_initialized = 0, last_review_requested = 0, updated_at = ? - WHERE task_id = ?`, now, taskID); err != nil { + SET review_request_initialized = FALSE, last_review_requested = FALSE, updated_at = ? + WHERE task_id = ?`), now, taskID); err != nil { return err } } @@ -2544,7 +2683,7 @@ func resetTaskCIAutoFixStateForTask( taskID string, now time.Time, ) error { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_ci_pr_state SET auto_fix_round_count = 0, last_fix_signature = '', @@ -2555,7 +2694,7 @@ func resetTaskCIAutoFixStateForTask( last_error_kind = CASE WHEN auto_fix_exhausted_at IS NOT NULL THEN '' ELSE last_error_kind END, auto_fix_exhausted_at = NULL, updated_at = ? - WHERE task_id = ?`, now, taskID) + WHERE task_id = ?`), now, taskID) return err } @@ -2565,14 +2704,14 @@ func resetTaskCITerminalCheckpointForTask( taskID, state string, now time.Time, ) error { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_ci_pr_state SET last_observed_pr_state = '', last_lifecycle_event = '', last_lifecycle_prompt_at = NULL, last_lifecycle_session_id = NULL, updated_at = ? - WHERE task_id = ? AND (last_observed_pr_state = ? OR last_lifecycle_event = ?)`, + WHERE task_id = ? AND (last_observed_pr_state = ? OR last_lifecycle_event = ?)`), now, taskID, state, state) return err } @@ -2583,7 +2722,7 @@ func (s *Store) GetTaskPRAutomationOptions( ) (*TaskPRAutomationOptions, error) { var opts TaskPRAutomationOptions err := s.ro.GetContext(ctx, &opts, - `SELECT * FROM github_task_pr_automation_options WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, + s.ro.Rebind(`SELECT * FROM github_task_pr_automation_options WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), taskID, repositoryID, prNumber) if errors.Is(err, sql.ErrNoRows) { now := time.Now().UTC() @@ -2599,7 +2738,7 @@ func (s *Store) GetTaskPRAutomationOptions( func (s *Store) ListTaskPRAutomationOptions(ctx context.Context, taskID string) ([]*TaskPRAutomationOptions, error) { var rows []TaskPRAutomationOptions if err := s.ro.SelectContext(ctx, &rows, - `SELECT * FROM github_task_pr_automation_options WHERE task_id = ? ORDER BY repository_id ASC, pr_number ASC`, + s.ro.Rebind(`SELECT * FROM github_task_pr_automation_options WHERE task_id = ? ORDER BY repository_id ASC, pr_number ASC`), taskID); err != nil { return nil, err } @@ -2675,18 +2814,17 @@ func (s *Store) updateTaskPRAutomationOptionsTx( reviewerChanged bool, ) error { now := time.Now().UTC() - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO github_task_pr_automation_options ( - task_id, repository_id, pr_number, auto_fix_enabled, auto_merge_enabled, - prompt_on_review_requested, prompt_on_merged, prompt_on_closed, created_at, updated_at - ) VALUES (?, ?, ?, 0, 0, 0, 0, 0, ?, ?) - ON CONFLICT(task_id, repository_id, pr_number) DO NOTHING`, + task_id, repository_id, pr_number, created_at, updated_at + ) VALUES (?, ?, ?, ?, ?) + ON CONFLICT(task_id, repository_id, pr_number) DO NOTHING`), taskID, repositoryID, prNumber, now, now); err != nil { return err } var previous TaskPRAutomationOptions if err := tx.GetContext(ctx, &previous, - `SELECT * FROM github_task_pr_automation_options WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, + tx.Rebind(`SELECT * FROM github_task_pr_automation_options WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), taskID, repositoryID, prNumber); err != nil { return err } @@ -2695,7 +2833,7 @@ func (s *Store) updateTaskPRAutomationOptionsTx( reviewSet, reviewValue := boolPatchValue(patch.PromptOnReviewRequested) mergedSet, mergedValue := boolPatchValue(patch.PromptOnMerged) closedSet, closedValue := boolPatchValue(patch.PromptOnClosed) - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_pr_automation_options SET auto_fix_enabled = CASE WHEN ? THEN ? ELSE auto_fix_enabled END, auto_merge_enabled = CASE WHEN ? THEN ? ELSE auto_merge_enabled END, @@ -2703,7 +2841,7 @@ func (s *Store) updateTaskPRAutomationOptionsTx( prompt_on_merged = CASE WHEN ? THEN ? ELSE prompt_on_merged END, prompt_on_closed = CASE WHEN ? THEN ? ELSE prompt_on_closed END, updated_at = ? - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, + WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), autoFixSet, autoFixValue, autoMergeSet, autoMergeValue, reviewSet, reviewValue, mergedSet, mergedValue, closedSet, closedValue, now, taskID, repositoryID, prNumber); err != nil { @@ -2735,10 +2873,10 @@ func applyTaskPRAutomationOptionResets( if shouldResetReviewRequests( patch.PromptOnReviewRequested, previous.PromptOnReviewRequested, reviewerChanged, ) { - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_ci_pr_state - SET review_request_initialized = 0, last_review_requested = 0, updated_at = ? - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, + SET review_request_initialized = FALSE, last_review_requested = FALSE, updated_at = ? + WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), now, taskID, repositoryID, prNumber); err != nil { return err } @@ -2773,7 +2911,7 @@ func resetTaskCIAutoFixState( prNumber int, now time.Time, ) error { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_ci_pr_state SET auto_fix_round_count = 0, last_fix_signature = '', @@ -2784,7 +2922,7 @@ func resetTaskCIAutoFixState( last_error_kind = CASE WHEN auto_fix_exhausted_at IS NOT NULL THEN '' ELSE last_error_kind END, auto_fix_exhausted_at = NULL, updated_at = ? - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, now, taskID, repositoryID, prNumber) + WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), now, taskID, repositoryID, prNumber) return err } @@ -2796,7 +2934,7 @@ func resetTaskCITerminalCheckpoint( state string, now time.Time, ) error { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_ci_pr_state SET last_observed_pr_state = '', last_lifecycle_event = '', @@ -2804,7 +2942,7 @@ func resetTaskCITerminalCheckpoint( last_lifecycle_session_id = NULL, updated_at = ? WHERE task_id = ? AND repository_id = ? AND pr_number = ? - AND (last_observed_pr_state = ? OR last_lifecycle_event = ?)`, + AND (last_observed_pr_state = ? OR last_lifecycle_event = ?)`), now, taskID, repositoryID, prNumber, state, state) return err } @@ -2820,7 +2958,8 @@ func (s *Store) RebindTaskPRReviewer(ctx context.Context, taskID, login string) defer func() { _ = tx.Rollback() }() var current TaskCIOptions - err = tx.GetContext(ctx, ¤t, `SELECT * FROM github_task_ci_options WHERE task_id = ?`, taskID) + err = tx.GetContext(ctx, ¤t, + tx.Rebind(`SELECT * FROM github_task_ci_options WHERE task_id = ?`), taskID) if errors.Is(err, sql.ErrNoRows) { return false, nil } @@ -2834,10 +2973,12 @@ func (s *Store) RebindTaskPRReviewer(ctx context.Context, taskID, login string) if err != nil { return false, err } - if _, err := tx.ExecContext(ctx, `UPDATE github_task_ci_options SET review_reviewer_login = ?, updated_at = ? WHERE task_id = ?`, login, version, taskID); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind( + `UPDATE github_task_ci_options SET review_reviewer_login = ?, updated_at = ? WHERE task_id = ?`), login, version, taskID); err != nil { return false, err } - if _, err := tx.ExecContext(ctx, `UPDATE github_task_ci_pr_state SET review_request_initialized = 0, last_review_requested = 0, updated_at = ? WHERE task_id = ?`, version, taskID); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind( + `UPDATE github_task_ci_pr_state SET review_request_initialized = FALSE, last_review_requested = FALSE, updated_at = ? WHERE task_id = ?`), version, taskID); err != nil { return false, err } if err := tx.Commit(); err != nil { @@ -2850,7 +2991,7 @@ func (s *Store) RebindTaskPRReviewer(ctx context.Context, taskID, login string) func (s *Store) ListTaskCIPRStates(ctx context.Context, taskID string) ([]*TaskCIPRAutomationState, error) { var rows []TaskCIPRAutomationState if err := s.ro.SelectContext(ctx, &rows, - `SELECT * FROM github_task_ci_pr_state WHERE task_id = ? ORDER BY repository_id ASC, pr_number ASC`, + s.ro.Rebind(`SELECT * FROM github_task_ci_pr_state WHERE task_id = ? ORDER BY repository_id ASC, pr_number ASC`), taskID); err != nil { return nil, err } @@ -2865,9 +3006,9 @@ func (s *Store) ListTaskCIPRStates(ctx context.Context, taskID string) ([]*TaskC func (s *Store) GetTaskCIPRState(ctx context.Context, taskID, repositoryID string, prNumber int) (*TaskCIPRAutomationState, error) { var state TaskCIPRAutomationState err := s.ro.GetContext(ctx, &state, - `SELECT * FROM github_task_ci_pr_state + s.ro.Rebind(`SELECT * FROM github_task_ci_pr_state WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, - taskID, repositoryID, prNumber) + ), taskID, repositoryID, prNumber) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -2885,7 +3026,7 @@ func (s *Store) RecordTaskCIFixAttempt(ctx context.Context, attempt TaskCIFixAtt roundCount = 1 } return s.mutateTaskCIPRState(ctx, attempt.TaskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO github_task_ci_pr_state ( task_id, repository_id, pr_number, last_fix_signature, last_fix_checkpoint_json, last_fix_enqueued_at, last_fix_session_id, auto_fix_round_count, auto_fix_exhausted_at, @@ -2906,7 +3047,7 @@ func (s *Store) RecordTaskCIFixAttempt(ctx context.Context, attempt TaskCIFixAtt ELSE github_task_ci_pr_state.last_queue_removal_cause END, last_error = NULL, last_error_kind = '', - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), attempt.TaskID, attempt.RepositoryID, attempt.PRNumber, attempt.Signature, attempt.CheckpointJSON, when, nullableString(attempt.SessionID), roundCount, attempt.QueueRemovalEventID, attempt.QueueRemovalCause, now, now) @@ -2917,7 +3058,7 @@ func (s *Store) RecordTaskCIFixAttempt(ctx context.Context, attempt TaskCIFixAtt // RefreshTaskCIFixCheckpoint updates the current feedback checkpoint without recording a new prompt dispatch. func (s *Store) RefreshTaskCIFixCheckpoint(ctx context.Context, taskID, repositoryID string, prNumber int, signature, checkpointJSON string) error { return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO github_task_ci_pr_state ( task_id, repository_id, pr_number, last_fix_signature, last_fix_checkpoint_json, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?) @@ -2928,7 +3069,7 @@ func (s *Store) RefreshTaskCIFixCheckpoint(ctx context.Context, taskID, reposito last_fix_session_id = NULL, last_error = NULL, last_error_kind = '', - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), taskID, repositoryID, prNumber, signature, checkpointJSON, now, now) return err }) @@ -2950,16 +3091,16 @@ func (s *Store) AuthorizeTaskCIMergeRetry( } expiredBefore := requestedAt.Add(-taskCIMergeRetryInFlightTTL) return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error { - result, err := tx.ExecContext(ctx, ` + result, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_ci_pr_state SET - merge_retry_pending = 1, + merge_retry_pending = TRUE, updated_at = ? WHERE task_id = ? AND repository_id = ? AND pr_number = ? - AND merge_retry_pending = 0 + AND merge_retry_pending = FALSE AND ( (last_merge_result = ? AND last_error_kind = ?) OR (last_merge_result = ? AND last_merge_attempt_at <= ?) - )`, + )`), now, taskID, repositoryID, prNumber, TaskCIMergeResultFailed, TaskCIErrorKindAutoMerge, TaskCIMergeResultInFlight, expiredBefore) @@ -2984,11 +3125,11 @@ func (s *Store) ClearTaskCIMergeRetryAuthorization( ctx context.Context, taskID, repositoryID string, prNumber int, ) error { return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_ci_pr_state - SET merge_retry_pending = 0, updated_at = ? + SET merge_retry_pending = FALSE, updated_at = ? WHERE task_id = ? AND repository_id = ? AND pr_number = ? - AND merge_retry_pending = 1`, + AND merge_retry_pending = TRUE`), now, taskID, repositoryID, prNumber) return err }) @@ -3003,16 +3144,16 @@ func (s *Store) RecordTaskCIMergeAttempt(ctx context.Context, attempt TaskCIMerg when = time.Now().UTC() } return s.mutateTaskCIPRState(ctx, attempt.TaskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error { - result, err := tx.ExecContext(ctx, ` + result, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO github_task_ci_pr_state ( task_id, repository_id, pr_number, last_merge_signature, last_merge_attempt_at, last_merge_result, merge_retry_pending, last_queue_attempt_head_sha, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, 0, ?, ?, ?) + ) VALUES (?, ?, ?, ?, ?, ?, FALSE, ?, ?, ?) ON CONFLICT(task_id, repository_id, pr_number) DO UPDATE SET last_merge_signature = excluded.last_merge_signature, last_merge_attempt_at = excluded.last_merge_attempt_at, last_merge_result = excluded.last_merge_result, - merge_retry_pending = 0, + merge_retry_pending = FALSE, last_queue_attempt_head_sha = CASE WHEN excluded.last_queue_attempt_head_sha <> '' THEN excluded.last_queue_attempt_head_sha ELSE github_task_ci_pr_state.last_queue_attempt_head_sha END, @@ -3022,7 +3163,7 @@ func (s *Store) RecordTaskCIMergeAttempt(ctx context.Context, attempt TaskCIMerg THEN '' ELSE github_task_ci_pr_state.last_error_kind END, updated_at = excluded.updated_at WHERE github_task_ci_pr_state.last_merge_signature <> excluded.last_merge_signature - OR github_task_ci_pr_state.merge_retry_pending = 1`, + OR github_task_ci_pr_state.merge_retry_pending = TRUE`), attempt.TaskID, attempt.RepositoryID, attempt.PRNumber, attempt.Signature, when, TaskCIMergeResultInFlight, attempt.AttemptedHeadSHA, now, now, TaskCIErrorKindAutoMerge, TaskCIErrorKindAutoMerge) @@ -3052,7 +3193,7 @@ func (s *Store) RecordTaskCIMergeAttemptResult( return fmt.Errorf("invalid CI auto-merge result %q", result) } return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error { - outcome, err := tx.ExecContext(ctx, ` + outcome, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_ci_pr_state SET last_merge_result = ?, last_error = CASE @@ -3065,7 +3206,7 @@ func (s *Store) RecordTaskCIMergeAttemptResult( ELSE last_error_kind END, updated_at = ? WHERE task_id = ? AND repository_id = ? AND pr_number = ? - AND last_merge_signature = ?`, + AND last_merge_signature = ?`), result, result, TaskCIMergeResultFailed, strings.TrimSpace(message), result, TaskCIMergeResultAccepted, TaskCIErrorKindAutoMerge, @@ -3101,7 +3242,7 @@ func (s *Store) RecordTaskCIMergeQueueObservation(ctx context.Context, observati if observation.ActiveQueueHeadSHA == "" { baselineHead = observation.RemovalObservedHeadSHA } - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO github_task_ci_pr_state ( task_id, repository_id, pr_number, last_merge_signature, last_merge_result, last_queue_attempt_head_sha, last_queue_removal_cause, created_at, updated_at @@ -3114,7 +3255,7 @@ func (s *Store) RecordTaskCIMergeQueueObservation(ctx context.Context, observati WHEN excluded.last_merge_result <> '' THEN excluded.last_merge_result ELSE github_task_ci_pr_state.last_merge_result END, merge_retry_pending = CASE - WHEN excluded.last_merge_result = ? THEN 0 + WHEN excluded.last_merge_result = ? THEN FALSE ELSE github_task_ci_pr_state.merge_retry_pending END, last_queue_attempt_head_sha = CASE WHEN excluded.last_queue_attempt_head_sha <> '' @@ -3130,7 +3271,7 @@ func (s *Store) RecordTaskCIMergeQueueObservation(ctx context.Context, observati last_error_kind = CASE WHEN excluded.last_merge_result = ? AND github_task_ci_pr_state.last_error_kind = ? THEN '' ELSE github_task_ci_pr_state.last_error_kind END, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), observation.TaskID, observation.RepositoryID, observation.PRNumber, observation.MergeSignature, mergeResult, observation.ActiveQueueHeadSHA, observation.RemovalCause, now, now, @@ -3143,11 +3284,11 @@ func (s *Store) RecordTaskCIMergeQueueObservation(ctx context.Context, observati if baselineHead == "" { return nil } - _, err = tx.ExecContext(ctx, ` + _, err = tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_ci_pr_state SET last_queue_attempt_head_sha = ?, updated_at = ? WHERE task_id = ? AND repository_id = ? AND pr_number = ? - AND last_queue_attempt_head_sha = ''`, + AND last_queue_attempt_head_sha = ''`), baselineHead, now, observation.TaskID, observation.RepositoryID, observation.PRNumber) return err }) @@ -3165,14 +3306,14 @@ func (s *Store) RecordTaskCIAutoMergeError(ctx context.Context, taskID, reposito func (s *Store) recordTaskCIError(ctx context.Context, taskID, repositoryID string, prNumber int, kind, message string) error { return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO github_task_ci_pr_state ( task_id, repository_id, pr_number, last_error, last_error_kind, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(task_id, repository_id, pr_number) DO UPDATE SET last_error = excluded.last_error, last_error_kind = excluded.last_error_kind, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), taskID, repositoryID, prNumber, strings.TrimSpace(message), kind, now, now) return err }) @@ -3181,7 +3322,7 @@ func (s *Store) recordTaskCIError(ctx context.Context, taskID, repositoryID stri // MarkTaskCIAutoFixExhausted records that auto-fix reached its per-PR round cap. func (s *Store) MarkTaskCIAutoFixExhausted(ctx context.Context, taskID, repositoryID string, prNumber int, message string) error { return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO github_task_ci_pr_state ( task_id, repository_id, pr_number, auto_fix_exhausted_at, last_error, last_error_kind, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) @@ -3189,7 +3330,7 @@ func (s *Store) MarkTaskCIAutoFixExhausted(ctx context.Context, taskID, reposito auto_fix_exhausted_at = excluded.auto_fix_exhausted_at, last_error = excluded.last_error, last_error_kind = excluded.last_error_kind, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), taskID, repositoryID, prNumber, now, strings.TrimSpace(message), TaskCIErrorKindAutoFix, now, now) return err }) @@ -3198,9 +3339,9 @@ func (s *Store) MarkTaskCIAutoFixExhausted(ctx context.Context, taskID, reposito // ClearTaskCIError clears the latest CI automation error for a task PR. func (s *Store) ClearTaskCIError(ctx context.Context, taskID, repositoryID string, prNumber int) error { return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_ci_pr_state SET last_error = NULL, last_error_kind = '', updated_at = ? - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, + WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), now, taskID, repositoryID, prNumber) return err }) @@ -3211,15 +3352,15 @@ func (s *Store) SetTaskPRReviewRequestState( ctx context.Context, taskID, repositoryID string, prNumber int, requested bool, ) error { return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO github_task_ci_pr_state ( task_id, repository_id, pr_number, review_request_initialized, last_review_requested, created_at, updated_at - ) VALUES (?, ?, ?, 1, ?, ?, ?) + ) VALUES (?, ?, ?, TRUE, ?, ?, ?) ON CONFLICT(task_id, repository_id, pr_number) DO UPDATE SET - review_request_initialized = 1, + review_request_initialized = TRUE, last_review_requested = excluded.last_review_requested, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), taskID, repositoryID, prNumber, requested, now, now) return err }) @@ -3230,7 +3371,7 @@ func (s *Store) SetTaskPRObservedState( ctx context.Context, taskID, repositoryID string, prNumber int, state string, ) error { return s.mutateTaskCIPRState(ctx, taskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO github_task_ci_pr_state ( task_id, repository_id, pr_number, last_observed_pr_state, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?) @@ -3240,7 +3381,7 @@ func (s *Store) SetTaskPRObservedState( WHEN excluded.last_observed_pr_state IN ('merged', 'closed') THEN github_task_ci_pr_state.last_lifecycle_event ELSE '' END, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), taskID, repositoryID, prNumber, state, now, now) return err }) @@ -3253,7 +3394,7 @@ func (s *Store) RecordTaskPRLifecyclePrompt(ctx context.Context, prompt TaskPRLi when = time.Now().UTC() } return s.mutateTaskCIPRState(ctx, prompt.TaskID, func(ctx context.Context, tx *sqlx.Tx, now time.Time) error { - _, err := tx.ExecContext(ctx, ` + _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO github_task_ci_pr_state ( task_id, repository_id, pr_number, review_request_initialized, last_review_requested, last_observed_pr_state, last_lifecycle_event, @@ -3261,7 +3402,7 @@ func (s *Store) RecordTaskPRLifecyclePrompt(ctx context.Context, prompt TaskPRLi ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(task_id, repository_id, pr_number) DO UPDATE SET review_request_initialized = CASE - WHEN excluded.last_lifecycle_event = 'review_requested' THEN 1 + WHEN excluded.last_lifecycle_event = 'review_requested' THEN TRUE ELSE github_task_ci_pr_state.review_request_initialized END, last_review_requested = CASE WHEN excluded.last_lifecycle_event = 'review_requested' THEN excluded.last_review_requested @@ -3274,7 +3415,7 @@ func (s *Store) RecordTaskPRLifecyclePrompt(ctx context.Context, prompt TaskPRLi last_lifecycle_session_id = excluded.last_lifecycle_session_id, last_error = NULL, last_error_kind = '', - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), prompt.TaskID, prompt.RepositoryID, prompt.PRNumber, prompt.Event == "review_requested", prompt.ReviewRequested, prompt.ObservedState, prompt.Event, when, nullableString(prompt.SessionID), now, now) @@ -3330,11 +3471,11 @@ func (s *Store) CreateReviewWatch(ctx context.Context, rw *ReviewWatch) error { return fmt.Errorf("marshal repos: %w", err) } rw.ReposJSON = string(reposJSON) - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO github_review_watches (id, workspace_id, workflow_id, workflow_step_id, repos, agent_profile_id, executor_profile_id, prompt, review_scope, custom_query, target_login, enabled, poll_interval_seconds, cleanup_policy, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`), rw.ID, rw.WorkspaceID, rw.WorkflowID, rw.WorkflowStepID, rw.ReposJSON, rw.AgentProfileID, rw.ExecutorProfileID, rw.Prompt, rw.ReviewScope, rw.CustomQuery, rw.TargetLogin, rw.Enabled, rw.PollIntervalSeconds, rw.CleanupPolicy, rw.CreatedAt, rw.UpdatedAt) @@ -3360,7 +3501,7 @@ func hydrateReviewWatchRepos(rw *ReviewWatch) { // GetReviewWatch returns a review watch by ID. func (s *Store) GetReviewWatch(ctx context.Context, id string) (*ReviewWatch, error) { var rw ReviewWatch - err := s.ro.GetContext(ctx, &rw, `SELECT * FROM github_review_watches WHERE id = ?`, id) + err := s.ro.GetContext(ctx, &rw, s.ro.Rebind(`SELECT * FROM github_review_watches WHERE id = ?`), id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -3375,7 +3516,7 @@ func (s *Store) GetReviewWatch(ctx context.Context, id string) (*ReviewWatch, er func (s *Store) ListReviewWatches(ctx context.Context, workspaceID string) ([]*ReviewWatch, error) { var watches []*ReviewWatch err := s.ro.SelectContext(ctx, &watches, - `SELECT * FROM github_review_watches WHERE workspace_id = ? ORDER BY created_at`, workspaceID) + s.ro.Rebind(`SELECT * FROM github_review_watches WHERE workspace_id = ? ORDER BY created_at`), workspaceID) if err != nil { return nil, err } @@ -3404,7 +3545,7 @@ func (s *Store) ListAllReviewWatches(ctx context.Context) ([]*ReviewWatch, error func (s *Store) ListEnabledReviewWatches(ctx context.Context) ([]*ReviewWatch, error) { var watches []*ReviewWatch err := s.ro.SelectContext(ctx, &watches, - `SELECT * FROM github_review_watches WHERE enabled = 1 ORDER BY created_at`) + s.ro.Rebind(`SELECT * FROM github_review_watches WHERE enabled = TRUE ORDER BY created_at`)) if err != nil { return nil, err } @@ -3423,12 +3564,12 @@ func (s *Store) UpdateReviewWatch(ctx context.Context, rw *ReviewWatch) error { return fmt.Errorf("marshal repos: %w", err) } rw.ReposJSON = string(reposJSON) - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` UPDATE github_review_watches SET workflow_id = ?, workflow_step_id = ?, repos = ?, agent_profile_id = ?, executor_profile_id = ?, prompt = ?, review_scope = ?, custom_query = ?, target_login = ?, enabled = ?, poll_interval_seconds = ?, cleanup_policy = ?, last_polled_at = ?, updated_at = ? - WHERE id = ?`, + WHERE id = ?`), rw.WorkflowID, rw.WorkflowStepID, rw.ReposJSON, rw.AgentProfileID, rw.ExecutorProfileID, rw.Prompt, rw.ReviewScope, rw.CustomQuery, rw.TargetLogin, @@ -3447,10 +3588,10 @@ func (s *Store) DeleteReviewWatch(ctx context.Context, id string) error { return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, `DELETE FROM github_review_pr_tasks WHERE review_watch_id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind(`DELETE FROM github_review_pr_tasks WHERE review_watch_id = ?`), id); err != nil { return err } - if _, err := tx.ExecContext(ctx, `DELETE FROM github_review_watches WHERE id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind(`DELETE FROM github_review_watches WHERE id = ?`), id); err != nil { return err } return tx.Commit() @@ -3462,10 +3603,10 @@ func (s *Store) DeleteReviewWatch(ctx context.Context, id string) error { // watcher's bound agent profile is detected as soft-deleted. func (s *Store) DisableReviewWatchWithError(ctx context.Context, id, cause string) error { now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, + _, err := s.db.ExecContext(ctx, s.db.Rebind( `UPDATE github_review_watches - SET enabled = 0, last_error = ?, last_error_at = ?, updated_at = ? - WHERE id = ?`, + SET enabled = FALSE, last_error = ?, last_error_at = ?, updated_at = ? + WHERE id = ?`), cause, now, now, id) return err } @@ -3478,9 +3619,9 @@ func (s *Store) CreateReviewPRTask(ctx context.Context, rpt *ReviewPRTask) error rpt.ID = uuid.New().String() } rpt.CreatedAt = time.Now().UTC() - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO github_review_pr_tasks (id, review_watch_id, repo_owner, repo_name, pr_number, pr_url, task_id, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?)`), rpt.ID, rpt.ReviewWatchID, rpt.RepoOwner, rpt.RepoName, rpt.PRNumber, rpt.PRURL, rpt.TaskID, rpt.CreatedAt) return err } @@ -3488,22 +3629,23 @@ func (s *Store) CreateReviewPRTask(ctx context.Context, rpt *ReviewPRTask) error // HasReviewPRTask checks if a task was already created for a PR in a review watch. func (s *Store) HasReviewPRTask(ctx context.Context, reviewWatchID, repoOwner, repoName string, prNumber int) (bool, error) { var count int - err := s.ro.GetContext(ctx, &count, - `SELECT COUNT(*) FROM github_review_pr_tasks WHERE review_watch_id = ? AND repo_owner = ? AND repo_name = ? AND pr_number = ?`, + err := s.ro.GetContext(ctx, &count, s.ro.Rebind( + `SELECT COUNT(*) FROM github_review_pr_tasks WHERE review_watch_id = ? AND repo_owner = ? AND repo_name = ? AND pr_number = ?`), reviewWatchID, repoOwner, repoName, prNumber) return count > 0, err } // ReserveReviewPRTask atomically claims a slot for a (watch, repo, PR) tuple -// using INSERT OR IGNORE against the UNIQUE constraint. Returns true if this +// using the UNIQUE constraint. Returns true if this // caller won the race and should proceed to create the task, false if another // caller already holds the slot. The caller is expected to call // AssignReviewPRTaskID once the task is created, or ReleaseReviewPRTask if // task creation fails. func (s *Store) ReserveReviewPRTask(ctx context.Context, reviewWatchID, repoOwner, repoName string, prNumber int, prURL string) (bool, error) { - res, err := s.db.ExecContext(ctx, ` - INSERT OR IGNORE INTO github_review_pr_tasks (id, review_watch_id, repo_owner, repo_name, pr_number, pr_url, task_id, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + res, err := s.db.ExecContext(ctx, s.db.Rebind(` + INSERT INTO github_review_pr_tasks (id, review_watch_id, repo_owner, repo_name, pr_number, pr_url, task_id, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(review_watch_id, repo_owner, repo_name, pr_number) DO NOTHING`), uuid.New().String(), reviewWatchID, repoOwner, repoName, prNumber, prURL, "", time.Now().UTC()) if err != nil { return false, err @@ -3521,9 +3663,9 @@ func (s *Store) ReserveReviewPRTask(ctx context.Context, reviewWatchID, repoOwne // the reservation was removed (e.g. by a concurrent cleanup sweep) between // Reserve and Assign — otherwise the task would leak with no dedup record. func (s *Store) AssignReviewPRTaskID(ctx context.Context, reviewWatchID, repoOwner, repoName string, prNumber int, taskID string) error { - res, err := s.db.ExecContext(ctx, ` + res, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE github_review_pr_tasks SET task_id = ? - WHERE review_watch_id = ? AND repo_owner = ? AND repo_name = ? AND pr_number = ?`, + WHERE review_watch_id = ? AND repo_owner = ? AND repo_name = ? AND pr_number = ?`), taskID, reviewWatchID, repoOwner, repoName, prNumber) if err != nil { return err @@ -3542,9 +3684,9 @@ func (s *Store) AssignReviewPRTaskID(ctx context.Context, reviewWatchID, repoOwn // Used when task creation fails so a later poll can retry instead of the PR // being permanently blocked by an orphan reservation. func (s *Store) ReleaseReviewPRTask(ctx context.Context, reviewWatchID, repoOwner, repoName string, prNumber int) error { - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` DELETE FROM github_review_pr_tasks - WHERE review_watch_id = ? AND repo_owner = ? AND repo_name = ? AND pr_number = ?`, + WHERE review_watch_id = ? AND repo_owner = ? AND repo_name = ? AND pr_number = ?`), reviewWatchID, repoOwner, repoName, prNumber) return err } @@ -3552,9 +3694,9 @@ func (s *Store) ReleaseReviewPRTask(ctx context.Context, reviewWatchID, repoOwne // ListReviewPRTasksByWatch lists all dedup records for a given review watch. func (s *Store) ListReviewPRTasksByWatch(ctx context.Context, watchID string) ([]*ReviewPRTask, error) { var tasks []*ReviewPRTask - err := s.ro.SelectContext(ctx, &tasks, + err := s.ro.SelectContext(ctx, &tasks, s.ro.Rebind( `SELECT id, review_watch_id, repo_owner, repo_name, pr_number, pr_url, task_id, created_at - FROM github_review_pr_tasks WHERE review_watch_id = ?`, watchID) + FROM github_review_pr_tasks WHERE review_watch_id = ?`), watchID) return tasks, err } @@ -3571,7 +3713,7 @@ func (s *Store) ListAllReviewPRTasks(ctx context.Context) ([]*ReviewPRTask, erro // DeleteReviewPRTask deletes a dedup record by ID. func (s *Store) DeleteReviewPRTask(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM github_review_pr_tasks WHERE id = ?`, id) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM github_review_pr_tasks WHERE id = ?`), id) return err } @@ -3581,7 +3723,7 @@ func (s *Store) DeleteReviewPRTask(ctx context.Context, id string) error { func (s *Store) ListReviewPRTaskIDsByWatch(ctx context.Context, watchID string) ([]string, error) { var ids []string err := s.ro.SelectContext(ctx, &ids, - `SELECT task_id FROM github_review_pr_tasks WHERE review_watch_id = ?`, watchID) + s.ro.Rebind(`SELECT task_id FROM github_review_pr_tasks WHERE review_watch_id = ?`), watchID) return ids, err } @@ -3595,12 +3737,12 @@ func (s *Store) ResetReviewWatchState(ctx context.Context, watchID string) error return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, - `DELETE FROM github_review_pr_tasks WHERE review_watch_id = ?`, watchID); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind( + `DELETE FROM github_review_pr_tasks WHERE review_watch_id = ?`), watchID); err != nil { return err } - if _, err := tx.ExecContext(ctx, - `UPDATE github_review_watches SET last_polled_at = NULL, updated_at = ? WHERE id = ?`, + if _, err := tx.ExecContext(ctx, s.db.Rebind( + `UPDATE github_review_watches SET last_polled_at = NULL, updated_at = ? WHERE id = ?`), time.Now().UTC(), watchID); err != nil { return err } @@ -3653,11 +3795,11 @@ func (s *Store) GetPRStats(ctx context.Context, req *PRStatsRequest) (*PRStats, func (s *Store) runPRStatsQueries(ctx context.Context, q *prStatsQuery) (*PRStats, error) { stats := &PRStats{} - if err := s.ro.GetContext(ctx, &stats.TotalPRsCreated, q.build("COUNT(*)", ""), q.args...); err != nil { + if err := s.ro.GetContext(ctx, &stats.TotalPRsCreated, s.ro.Rebind(q.build("COUNT(*)", "")), q.args...); err != nil { return nil, err } if err := s.ro.GetContext(ctx, &stats.TotalComments, - q.build("COALESCE(SUM(gtp.comment_count), 0)", ""), q.args...); err != nil { + s.ro.Rebind(q.build("COALESCE(SUM(gtp.comment_count), 0)", "")), q.args...); err != nil { return nil, err } if err := s.fetchCIPassRate(ctx, q, stats); err != nil { @@ -3668,17 +3810,19 @@ func (s *Store) runPRStatsQueries(ctx context.Context, q *prStatsQuery) (*PRStat } var avgMerge sql.NullFloat64 - avgQ := q.build("AVG((julianday(gtp.merged_at) - julianday(gtp.created_at)) * 24)", "gtp.merged_at IS NOT NULL") - if err := s.ro.GetContext(ctx, &avgMerge, avgQ, q.args...); err != nil { + avgDuration := fmt.Sprintf("(%s) / 3600000.0", dialect.DurationMs(s.ro.DriverName(), "gtp.merged_at", "gtp.created_at")) + avgQ := q.build("AVG("+avgDuration+")", "gtp.merged_at IS NOT NULL") + if err := s.ro.GetContext(ctx, &avgMerge, s.ro.Rebind(avgQ), q.args...); err != nil { return nil, err } if avgMerge.Valid { stats.AvgTimeToMergeHours = avgMerge.Float64 } - dailyQ := q.build("date(gtp.created_at) as date, COUNT(*) as count", "") + - " GROUP BY date(gtp.created_at) ORDER BY date" - if err := s.ro.SelectContext(ctx, &stats.PRsByDay, dailyQ, q.args...); err != nil { + dailyDate := dialect.DateOf(s.ro.DriverName(), "gtp.created_at") + dailyQ := q.build(dailyDate+" as date, COUNT(*) as count", "") + + " GROUP BY " + dailyDate + " ORDER BY date" + if err := s.ro.SelectContext(ctx, &stats.PRsByDay, s.ro.Rebind(dailyQ), q.args...); err != nil { return nil, err } return stats, nil @@ -3687,11 +3831,11 @@ func (s *Store) runPRStatsQueries(ctx context.Context, q *prStatsQuery) (*PRStat func (s *Store) fetchCIPassRate(ctx context.Context, q *prStatsQuery, stats *PRStats) error { var totalWithChecks, passed int if err := s.ro.GetContext(ctx, &totalWithChecks, - q.build("COUNT(*)", "gtp.checks_state != ''"), q.args...); err != nil { + s.ro.Rebind(q.build("COUNT(*)", "gtp.checks_state != ''")), q.args...); err != nil { return err } if err := s.ro.GetContext(ctx, &passed, - q.build("COUNT(*)", "gtp.checks_state = 'success'"), q.args...); err != nil { + s.ro.Rebind(q.build("COUNT(*)", "gtp.checks_state = 'success'")), q.args...); err != nil { return err } if totalWithChecks > 0 { @@ -3703,11 +3847,11 @@ func (s *Store) fetchCIPassRate(ctx context.Context, q *prStatsQuery, stats *PRS func (s *Store) fetchApprovalRate(ctx context.Context, q *prStatsQuery, stats *PRStats) error { var totalReviewed, approved int if err := s.ro.GetContext(ctx, &totalReviewed, - q.build("COUNT(*)", "gtp.review_state != ''"), q.args...); err != nil { + s.ro.Rebind(q.build("COUNT(*)", "gtp.review_state != ''")), q.args...); err != nil { return err } if err := s.ro.GetContext(ctx, &approved, - q.build("COUNT(*)", "gtp.review_state = 'approved'"), q.args...); err != nil { + s.ro.Rebind(q.build("COUNT(*)", "gtp.review_state = 'approved'")), q.args...); err != nil { return err } stats.TotalPRsReviewed = totalReviewed @@ -3761,11 +3905,11 @@ func (s *Store) CreateIssueWatch(ctx context.Context, iw *IssueWatch) error { return fmt.Errorf("marshal labels: %w", err) } iw.LabelsJSON = string(labelsJSON) - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO github_issue_watches (id, workspace_id, workflow_id, workflow_step_id, repos, agent_profile_id, executor_profile_id, prompt, labels, custom_query, enabled, poll_interval_seconds, cleanup_policy, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`), iw.ID, iw.WorkspaceID, iw.WorkflowID, iw.WorkflowStepID, iw.ReposJSON, iw.AgentProfileID, iw.ExecutorProfileID, iw.Prompt, iw.LabelsJSON, iw.CustomQuery, iw.Enabled, iw.PollIntervalSeconds, iw.CleanupPolicy, iw.CreatedAt, iw.UpdatedAt) @@ -3775,7 +3919,7 @@ func (s *Store) CreateIssueWatch(ctx context.Context, iw *IssueWatch) error { // GetIssueWatch returns an issue watch by ID. func (s *Store) GetIssueWatch(ctx context.Context, id string) (*IssueWatch, error) { var iw IssueWatch - err := s.ro.GetContext(ctx, &iw, `SELECT * FROM github_issue_watches WHERE id = ?`, id) + err := s.ro.GetContext(ctx, &iw, s.ro.Rebind(`SELECT * FROM github_issue_watches WHERE id = ?`), id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -3790,7 +3934,7 @@ func (s *Store) GetIssueWatch(ctx context.Context, id string) (*IssueWatch, erro func (s *Store) ListIssueWatches(ctx context.Context, workspaceID string) ([]*IssueWatch, error) { var watches []*IssueWatch err := s.ro.SelectContext(ctx, &watches, - `SELECT * FROM github_issue_watches WHERE workspace_id = ? ORDER BY created_at`, workspaceID) + s.ro.Rebind(`SELECT * FROM github_issue_watches WHERE workspace_id = ? ORDER BY created_at`), workspaceID) if err != nil { return nil, err } @@ -3818,7 +3962,7 @@ func (s *Store) ListAllIssueWatches(ctx context.Context) ([]*IssueWatch, error) func (s *Store) ListEnabledIssueWatches(ctx context.Context) ([]*IssueWatch, error) { var watches []*IssueWatch err := s.ro.SelectContext(ctx, &watches, - `SELECT * FROM github_issue_watches WHERE enabled = 1 ORDER BY created_at`) + s.ro.Rebind(`SELECT * FROM github_issue_watches WHERE enabled = TRUE ORDER BY created_at`)) if err != nil { return nil, err } @@ -3842,12 +3986,12 @@ func (s *Store) UpdateIssueWatch(ctx context.Context, iw *IssueWatch) error { return fmt.Errorf("marshal labels: %w", err) } iw.LabelsJSON = string(labelsJSON) - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` UPDATE github_issue_watches SET workflow_id = ?, workflow_step_id = ?, repos = ?, agent_profile_id = ?, executor_profile_id = ?, prompt = ?, labels = ?, custom_query = ?, enabled = ?, poll_interval_seconds = ?, cleanup_policy = ?, last_polled_at = ?, updated_at = ? - WHERE id = ?`, + WHERE id = ?`), iw.WorkflowID, iw.WorkflowStepID, iw.ReposJSON, iw.AgentProfileID, iw.ExecutorProfileID, iw.Prompt, iw.LabelsJSON, iw.CustomQuery, @@ -3862,10 +4006,10 @@ func (s *Store) DeleteIssueWatch(ctx context.Context, id string) error { return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, `DELETE FROM github_issue_watch_tasks WHERE issue_watch_id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind(`DELETE FROM github_issue_watch_tasks WHERE issue_watch_id = ?`), id); err != nil { return err } - if _, err := tx.ExecContext(ctx, `DELETE FROM github_issue_watches WHERE id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind(`DELETE FROM github_issue_watches WHERE id = ?`), id); err != nil { return err } return tx.Commit() @@ -3877,10 +4021,10 @@ func (s *Store) DeleteIssueWatch(ctx context.Context, id string) error { // watcher's bound agent profile is detected as soft-deleted. func (s *Store) DisableIssueWatchWithError(ctx context.Context, id, cause string) error { now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, + _, err := s.db.ExecContext(ctx, s.db.Rebind( `UPDATE github_issue_watches - SET enabled = 0, last_error = ?, last_error_at = ?, updated_at = ? - WHERE id = ?`, + SET enabled = FALSE, last_error = ?, last_error_at = ?, updated_at = ? + WHERE id = ?`), cause, now, now, id) return err } @@ -3890,9 +4034,10 @@ func (s *Store) DisableIssueWatchWithError(ctx context.Context, id, cause string // ReserveIssueWatchTask atomically claims a slot for a (watch, repo, issue) tuple. // Returns true if this caller won the race and should proceed to create the task. func (s *Store) ReserveIssueWatchTask(ctx context.Context, issueWatchID, repoOwner, repoName string, issueNumber int, issueURL string) (bool, error) { - res, err := s.db.ExecContext(ctx, ` - INSERT OR IGNORE INTO github_issue_watch_tasks (id, issue_watch_id, repo_owner, repo_name, issue_number, issue_url, task_id, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?)`, + res, err := s.db.ExecContext(ctx, s.db.Rebind(` + INSERT INTO github_issue_watch_tasks (id, issue_watch_id, repo_owner, repo_name, issue_number, issue_url, task_id, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(issue_watch_id, repo_owner, repo_name, issue_number) DO NOTHING`), uuid.New().String(), issueWatchID, repoOwner, repoName, issueNumber, issueURL, "", time.Now().UTC()) if err != nil { return false, err @@ -3906,9 +4051,9 @@ func (s *Store) ReserveIssueWatchTask(ctx context.Context, issueWatchID, repoOwn // AssignIssueWatchTaskID sets the task_id on a reserved dedup row. func (s *Store) AssignIssueWatchTaskID(ctx context.Context, issueWatchID, repoOwner, repoName string, issueNumber int, taskID string) error { - res, err := s.db.ExecContext(ctx, ` + res, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE github_issue_watch_tasks SET task_id = ? - WHERE issue_watch_id = ? AND repo_owner = ? AND repo_name = ? AND issue_number = ?`, + WHERE issue_watch_id = ? AND repo_owner = ? AND repo_name = ? AND issue_number = ?`), taskID, issueWatchID, repoOwner, repoName, issueNumber) if err != nil { return err @@ -3925,9 +4070,9 @@ func (s *Store) AssignIssueWatchTaskID(ctx context.Context, issueWatchID, repoOw // ReleaseIssueWatchTask removes a reservation for a (watch, repo, issue) tuple. func (s *Store) ReleaseIssueWatchTask(ctx context.Context, issueWatchID, repoOwner, repoName string, issueNumber int) error { - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` DELETE FROM github_issue_watch_tasks - WHERE issue_watch_id = ? AND repo_owner = ? AND repo_name = ? AND issue_number = ?`, + WHERE issue_watch_id = ? AND repo_owner = ? AND repo_name = ? AND issue_number = ?`), issueWatchID, repoOwner, repoName, issueNumber) return err } @@ -3935,8 +4080,8 @@ func (s *Store) ReleaseIssueWatchTask(ctx context.Context, issueWatchID, repoOwn // HasIssueWatchTask checks if a task was already created for an issue in an issue watch. func (s *Store) HasIssueWatchTask(ctx context.Context, issueWatchID, repoOwner, repoName string, issueNumber int) (bool, error) { var count int - err := s.ro.GetContext(ctx, &count, - `SELECT COUNT(*) FROM github_issue_watch_tasks WHERE issue_watch_id = ? AND repo_owner = ? AND repo_name = ? AND issue_number = ?`, + err := s.ro.GetContext(ctx, &count, s.ro.Rebind( + `SELECT COUNT(*) FROM github_issue_watch_tasks WHERE issue_watch_id = ? AND repo_owner = ? AND repo_name = ? AND issue_number = ?`), issueWatchID, repoOwner, repoName, issueNumber) return count > 0, err } @@ -3944,9 +4089,9 @@ func (s *Store) HasIssueWatchTask(ctx context.Context, issueWatchID, repoOwner, // ListIssueWatchTasksByWatch lists all dedup records for a given issue watch. func (s *Store) ListIssueWatchTasksByWatch(ctx context.Context, watchID string) ([]*IssueWatchTask, error) { var tasks []*IssueWatchTask - err := s.ro.SelectContext(ctx, &tasks, + err := s.ro.SelectContext(ctx, &tasks, s.ro.Rebind( `SELECT id, issue_watch_id, repo_owner, repo_name, issue_number, issue_url, task_id, created_at - FROM github_issue_watch_tasks WHERE issue_watch_id = ?`, watchID) + FROM github_issue_watch_tasks WHERE issue_watch_id = ?`), watchID) return tasks, err } @@ -3962,7 +4107,7 @@ func (s *Store) ListAllIssueWatchTasks(ctx context.Context) ([]*IssueWatchTask, // DeleteIssueWatchTask deletes a dedup record by ID. func (s *Store) DeleteIssueWatchTask(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM github_issue_watch_tasks WHERE id = ?`, id) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM github_issue_watch_tasks WHERE id = ?`), id) return err } @@ -3972,7 +4117,7 @@ func (s *Store) DeleteIssueWatchTask(ctx context.Context, id string) error { func (s *Store) ListIssueWatchTaskIDsByWatch(ctx context.Context, watchID string) ([]string, error) { var ids []string err := s.ro.SelectContext(ctx, &ids, - `SELECT task_id FROM github_issue_watch_tasks WHERE issue_watch_id = ?`, watchID) + s.ro.Rebind(`SELECT task_id FROM github_issue_watch_tasks WHERE issue_watch_id = ?`), watchID) return ids, err } @@ -3986,12 +4131,12 @@ func (s *Store) ResetIssueWatchState(ctx context.Context, watchID string) error return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, - `DELETE FROM github_issue_watch_tasks WHERE issue_watch_id = ?`, watchID); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind( + `DELETE FROM github_issue_watch_tasks WHERE issue_watch_id = ?`), watchID); err != nil { return err } - if _, err := tx.ExecContext(ctx, - `UPDATE github_issue_watches SET last_polled_at = NULL, updated_at = ? WHERE id = ?`, + if _, err := tx.ExecContext(ctx, s.db.Rebind( + `UPDATE github_issue_watches SET last_polled_at = NULL, updated_at = ? WHERE id = ?`), time.Now().UTC(), watchID); err != nil { return err } @@ -4115,11 +4260,11 @@ func (s *Store) GetWorkspaceSettings(ctx context.Context, workspaceID string) (* CreatedAt time.Time `db:"created_at"` UpdatedAt time.Time `db:"updated_at"` } - err := s.ro.GetContext(ctx, &row, ` + err := s.ro.GetContext(ctx, &row, s.ro.Rebind(` SELECT workspace_id, task_git_credentials_mode, repo_scope_mode, repo_scope_orgs, repo_scope_repos, saved_presets, default_query_presets, created_at, updated_at FROM github_workspace_settings - WHERE workspace_id = ?`, workspaceID) + WHERE workspace_id = ?`), workspaceID) if errors.Is(err, sql.ErrNoRows) { return defaultWorkspaceSettings(workspaceID), nil } @@ -4158,11 +4303,12 @@ func (s *Store) EnsureWorkspaceExecutorDefaults(ctx context.Context, workspaceID return fmt.Errorf("workspace_id is required") } now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, ` - INSERT OR IGNORE INTO github_workspace_settings ( + _, err := s.db.ExecContext(ctx, s.db.Rebind(` + INSERT INTO github_workspace_settings ( workspace_id, task_git_credentials_mode, repo_scope_mode, repo_scope_orgs, repo_scope_repos, saved_presets, default_query_presets, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(workspace_id) DO NOTHING`), workspaceID, TaskGitCredentialsModeExecutor, RepoScopeModeAll, "[]", "[]", "[]", nil, now, now) return err } @@ -4174,8 +4320,8 @@ func (s *Store) DeleteWorkspaceSettings(ctx context.Context, workspaceID string) if workspaceID == "" { return fmt.Errorf("workspace_id is required") } - _, err := s.db.ExecContext(ctx, - `DELETE FROM github_workspace_settings WHERE workspace_id = ?`, workspaceID) + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `DELETE FROM github_workspace_settings WHERE workspace_id = ?`), workspaceID) return err } @@ -4211,7 +4357,7 @@ func (s *Store) UpsertWorkspaceSettings(ctx context.Context, settings *Workspace defaults.Valid = true defaults.String = string(settings.DefaultQueryPresets) } - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO github_workspace_settings ( workspace_id, task_git_credentials_mode, repo_scope_mode, repo_scope_orgs, repo_scope_repos, saved_presets, default_query_presets, created_at, updated_at @@ -4223,7 +4369,7 @@ func (s *Store) UpsertWorkspaceSettings(ctx context.Context, settings *Workspace repo_scope_repos = excluded.repo_scope_repos, saved_presets = excluded.saved_presets, default_query_presets = excluded.default_query_presets, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), settings.WorkspaceID, settings.TaskGitCredentialsMode, settings.RepoScopeMode, string(orgsJSON), string(reposJSON), string(settings.SavedPresets), defaults, now, now) return err @@ -4237,11 +4383,12 @@ func (s *Store) PatchWorkspaceSettings(ctx context.Context, req *UpdateWorkspace } workspaceID := strings.TrimSpace(req.WorkspaceID) now := time.Now().UTC() - if _, err := s.db.ExecContext(ctx, ` - INSERT OR IGNORE INTO github_workspace_settings ( + if _, err := s.db.ExecContext(ctx, s.db.Rebind(` + INSERT INTO github_workspace_settings ( workspace_id, task_git_credentials_mode, repo_scope_mode, repo_scope_orgs, repo_scope_repos, saved_presets, default_query_presets, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(workspace_id) DO NOTHING`), workspaceID, TaskGitCredentialsModeManaged, RepoScopeModeAll, "[]", "[]", "[]", nil, now, now); err != nil { return nil, err } @@ -4263,7 +4410,7 @@ func (s *Store) PatchWorkspaceSettings(ctx context.Context, req *UpdateWorkspace patch.add("updated_at = ?", now) patch.args = append(patch.args, workspaceID) query := "UPDATE github_workspace_settings SET " + strings.Join(patch.sets, ", ") + " WHERE workspace_id = ?" - if _, err := s.db.ExecContext(ctx, query, patch.args...); err != nil { + if _, err := s.db.ExecContext(ctx, s.db.Rebind(query), patch.args...); err != nil { return nil, err } } @@ -4413,8 +4560,8 @@ func (s *Store) GetActionPresets(ctx context.Context, workspaceID string) (*Acti PRJSON string `db:"pr_presets"` IssueJSON string `db:"issue_presets"` } - err := s.ro.GetContext(ctx, &row, - `SELECT pr_presets, issue_presets FROM github_action_presets WHERE workspace_id = ?`, workspaceID) + err := s.ro.GetContext(ctx, &row, s.ro.Rebind( + `SELECT pr_presets, issue_presets FROM github_action_presets WHERE workspace_id = ?`), workspaceID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -4442,13 +4589,13 @@ func (s *Store) UpsertActionPresets(ctx context.Context, presets *ActionPresets) if err != nil { return fmt.Errorf("marshal issue presets: %w", err) } - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO github_action_presets (workspace_id, pr_presets, issue_presets, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(workspace_id) DO UPDATE SET pr_presets = excluded.pr_presets, issue_presets = excluded.issue_presets, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), presets.WorkspaceID, string(prJSON), string(issueJSON), time.Now().UTC()) return err } @@ -4456,6 +4603,6 @@ func (s *Store) UpsertActionPresets(ctx context.Context, presets *ActionPresets) // DeleteActionPresets removes the stored overrides for a workspace so defaults // apply again. func (s *Store) DeleteActionPresets(ctx context.Context, workspaceID string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM github_action_presets WHERE workspace_id = ?`, workspaceID) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM github_action_presets WHERE workspace_id = ?`), workspaceID) return err } diff --git a/apps/backend/internal/github/store_connections.go b/apps/backend/internal/github/store_connections.go index 8c1f58ebbe..d2db01a499 100644 --- a/apps/backend/internal/github/store_connections.go +++ b/apps/backend/internal/github/store_connections.go @@ -285,7 +285,11 @@ func (s *Store) UpsertUserConnection(ctx context.Context, connection *UserConnec INSERT INTO github_user_connection_versions (workspace_id, user_id, credential_generation, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(workspace_id, user_id) DO UPDATE SET - credential_generation = MAX(github_user_connection_versions.credential_generation, excluded.credential_generation), + credential_generation = CASE + WHEN github_user_connection_versions.credential_generation > excluded.credential_generation + THEN github_user_connection_versions.credential_generation + ELSE excluded.credential_generation + END, updated_at = excluded.updated_at`), connection.WorkspaceID, connection.UserID, connection.CredentialGeneration, connection.UpdatedAt); err != nil { return err @@ -305,10 +309,11 @@ func (s *Store) DeleteUserConnection(ctx context.Context, workspaceID, userID st VALUES (?, ?, COALESCE((SELECT credential_generation + 1 FROM github_user_connections WHERE workspace_id = ? AND user_id = ?), 1), ?) ON CONFLICT(workspace_id, user_id) DO UPDATE SET - credential_generation = MAX( - github_user_connection_versions.credential_generation + 1, - excluded.credential_generation - ), updated_at = excluded.updated_at`), + credential_generation = CASE + WHEN github_user_connection_versions.credential_generation + 1 > excluded.credential_generation + THEN github_user_connection_versions.credential_generation + 1 + ELSE excluded.credential_generation + END, updated_at = excluded.updated_at`), workspaceID, userID, workspaceID, userID, time.Now().UTC()); err != nil { return err } @@ -331,10 +336,11 @@ func (s *Store) DeleteUserConnectionsByWorkspace(ctx context.Context, workspaceI SELECT workspace_id, user_id, credential_generation + 1, ? FROM github_user_connections WHERE workspace_id = ? ON CONFLICT(workspace_id, user_id) DO UPDATE SET - credential_generation = MAX( - github_user_connection_versions.credential_generation + 1, - excluded.credential_generation - ), updated_at = excluded.updated_at`), time.Now().UTC(), workspaceID); err != nil { + credential_generation = CASE + WHEN github_user_connection_versions.credential_generation + 1 > excluded.credential_generation + THEN github_user_connection_versions.credential_generation + 1 + ELSE excluded.credential_generation + END, updated_at = excluded.updated_at`), time.Now().UTC(), workspaceID); err != nil { return err } if _, err := tx.ExecContext(ctx, tx.Rebind( diff --git a/apps/backend/internal/github/store_postgres_test.go b/apps/backend/internal/github/store_postgres_test.go new file mode 100644 index 0000000000..e1cd0c19f7 --- /dev/null +++ b/apps/backend/internal/github/store_postgres_test.go @@ -0,0 +1,266 @@ +package github + +import ( + "testing" + "time" + + "github.com/kandev/kandev/internal/testutil" +) + +func TestPostgresStoreSchemaReplay(t *testing.T) { + database := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t)) + if _, err := database.Exec(` + CREATE TABLE workspaces (id TEXT PRIMARY KEY); + CREATE TABLE tasks ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL, + archived_at TIMESTAMPTZ + )`); err != nil { + t.Fatalf("create prerequisite tables: %v", err) + } + if _, err := database.Exec(` + INSERT INTO workspaces (id) VALUES ('ws-1'); + INSERT INTO tasks (id, workspace_id, archived_at) VALUES ('task-1', 'ws-1', NULL)`); err != nil { + t.Fatalf("seed prerequisite rows: %v", err) + } + + if _, err := NewStore(database, database); err != nil { + t.Fatalf("first GitHub store schema init: %v", err) + } + store, err := NewStore(database, database) + if err != nil { + t.Fatalf("second GitHub store schema init: %v", err) + } + + ctx := t.Context() + now := time.Now().UTC() + registration := newAppRegistration("registration-postgres", 1001, "PostgreSQL", now) + if err := store.UpsertDeploymentAppRegistration(ctx, registration); err != nil { + t.Fatalf("upsert app registration: %v", err) + } + gotRegistration, err := store.GetAppRegistration(ctx, registration.ID) + if err != nil || gotRegistration == nil || gotRegistration.DisplayName != registration.DisplayName { + t.Fatalf("get app registration = %+v, err %v", gotRegistration, err) + } + + connection := &WorkspaceConnection{ + WorkspaceID: "ws-1", Source: ConnectionSourcePAT, GitHubHost: "github.com", + Login: "octocat", Status: ConnectionStatusActive, CreatedAt: now, + } + if err := store.UpsertWorkspaceConnection(ctx, connection); err != nil { + t.Fatalf("upsert workspace connection: %v", err) + } + gotConnection, err := store.GetWorkspaceConnection(ctx, "ws-1") + if err != nil || gotConnection == nil || gotConnection.Login != connection.Login { + t.Fatalf("get workspace connection = %+v, err %v", gotConnection, err) + } + + installationID := int64(2001) + appConnection := &WorkspaceConnection{ + WorkspaceID: "ws-1", + Source: ConnectionSourceGitHubAppInstallation, + GitHubHost: "github.com", + InstallationID: &installationID, + InstallationAccountLogin: "acme", + InstallationAccountType: "Organization", + AppRegistrationID: registration.ID, + Status: ConnectionStatusActive, + CredentialGeneration: 2, + } + if err := store.UpsertWorkspaceConnection(ctx, appConnection); err != nil { + t.Fatalf("upsert GitHub App workspace connection: %v", err) + } + userConnection := &UserConnection{ + WorkspaceID: "ws-1", + UserID: "user-1", + AppRegistrationID: registration.ID, + GitHubUserID: 2002, + Login: "octocat", + Status: ConnectionStatusActive, + AccessExpiresAt: now.Add(time.Hour), + CredentialGeneration: 1, + CreatedAt: now, + } + if err := store.UpsertUserConnection(ctx, userConnection); err != nil { + t.Fatalf("upsert personal GitHub connection: %v", err) + } + gotUserConnection, err := store.GetUserConnection(ctx, "ws-1", "user-1") + if err != nil || gotUserConnection == nil || gotUserConnection.Login != userConnection.Login { + t.Fatalf("get personal GitHub connection = %+v, err %v", gotUserConnection, err) + } + patConnection := &WorkspaceConnection{ + WorkspaceID: "ws-1", + Source: ConnectionSourcePAT, + GitHubHost: "github.com", + Login: "octocat", + Status: ConnectionStatusActive, + CredentialGeneration: 3, + } + if err := store.UpsertWorkspaceConnection(ctx, patConnection); err == nil { + t.Fatal("workspace App registration mismatch was accepted with a personal connection") + } + + watch := &PRWatch{ + WorkspaceID: "ws-1", SessionID: "session-1", TaskID: "task-1", RepositoryID: "repo-1", + Owner: "acme", Repo: "widget", PRNumber: 42, Branch: "feature/postgres", + } + if err := store.CreatePRWatch(ctx, watch); err != nil { + t.Fatalf("create PR watch: %v", err) + } + gotWatch, err := store.GetPRWatch(ctx, watch.ID) + if err != nil || gotWatch == nil || gotWatch.PRNumber != watch.PRNumber { + t.Fatalf("get PR watch = %+v, err %v", gotWatch, err) + } + + taskPR := &TaskPR{ + WorkspaceID: "ws-1", TaskID: "task-1", RepositoryID: "repo-1", Owner: "acme", Repo: "widget", + PRNumber: 42, PRURL: "https://github.com/acme/widget/pull/42", PRTitle: "PostgreSQL parity", + HeadBranch: "feature/postgres", BaseBranch: "main", AuthorLogin: "octocat", State: "open", + CreatedAt: now, + } + if err := store.CreateTaskPR(ctx, taskPR); err != nil { + t.Fatalf("create task PR: %v", err) + } + gotTaskPR, err := store.GetTaskPRByID(ctx, taskPR.ID) + if err != nil || gotTaskPR == nil || gotTaskPR.PRNumber != taskPR.PRNumber { + t.Fatalf("get task PR = %+v, err %v", gotTaskPR, err) + } + + if err := store.EnsureWorkspaceExecutorDefaults(ctx, "ws-1"); err != nil { + t.Fatalf("ensure workspace executor defaults: %v", err) + } + settings, err := store.GetWorkspaceSettings(ctx, "ws-1") + if err != nil || settings == nil || settings.TaskGitCredentialsMode != TaskGitCredentialsModeExecutor { + t.Fatalf("get workspace settings = %+v, err %v", settings, err) + } + if err := store.UpsertWorkspaceSettings(ctx, &WorkspaceSettings{ + WorkspaceID: "ws-1", + TaskGitCredentialsMode: TaskGitCredentialsModeManaged, + RepoScopeMode: RepoScopeModeOrgs, + RepoScopeOrgs: []string{"acme"}, + SavedPresets: []byte(`[{"name":"default"}]`), + }); err != nil { + t.Fatalf("upsert workspace settings: %v", err) + } + settings, err = store.GetWorkspaceSettings(ctx, "ws-1") + if err != nil || settings == nil || settings.TaskGitCredentialsMode != TaskGitCredentialsModeManaged { + t.Fatalf("get updated workspace settings = %+v, err %v", settings, err) + } + + reviewWatch := &ReviewWatch{ + WorkspaceID: "ws-1", + WorkflowID: "workflow-1", + WorkflowStepID: "step-1", + AgentProfileID: "agent-1", + ExecutorProfileID: "executor-1", + Repos: []RepoFilter{{Owner: "acme", Name: "widget"}}, + Enabled: true, + PollIntervalSeconds: 60, + } + if err := store.CreateReviewWatch(ctx, reviewWatch); err != nil { + t.Fatalf("create review watch: %v", err) + } + gotReviewWatch, err := store.GetReviewWatch(ctx, reviewWatch.ID) + if err != nil || gotReviewWatch == nil || len(gotReviewWatch.Repos) != 1 { + t.Fatalf("get review watch = %+v, err %v", gotReviewWatch, err) + } + reserved, err := store.ReserveReviewPRTask(ctx, reviewWatch.ID, "acme", "widget", 42, "https://github.com/acme/widget/pull/42") + if err != nil || !reserved { + t.Fatalf("reserve review PR task = %v, err %v", reserved, err) + } + reserved, err = store.ReserveReviewPRTask(ctx, reviewWatch.ID, "acme", "widget", 42, "https://github.com/acme/widget/pull/42") + if err != nil || reserved { + t.Fatalf("duplicate review PR reservation = %v, err %v", reserved, err) + } + if err := store.AssignReviewPRTaskID(ctx, reviewWatch.ID, "acme", "widget", 42, "task-1"); err != nil { + t.Fatalf("assign review PR task: %v", err) + } + + issueWatch := &IssueWatch{ + WorkspaceID: "ws-1", + WorkflowID: "workflow-1", + WorkflowStepID: "step-1", + AgentProfileID: "agent-1", + ExecutorProfileID: "executor-1", + Labels: []string{"bug"}, + Enabled: true, + PollIntervalSeconds: 60, + } + if err := store.CreateIssueWatch(ctx, issueWatch); err != nil { + t.Fatalf("create issue watch: %v", err) + } + gotIssueWatch, err := store.GetIssueWatch(ctx, issueWatch.ID) + if err != nil || gotIssueWatch == nil || len(gotIssueWatch.Labels) != 1 { + t.Fatalf("get issue watch = %+v, err %v", gotIssueWatch, err) + } + reserved, err = store.ReserveIssueWatchTask(ctx, issueWatch.ID, "acme", "widget", 7, "https://github.com/acme/widget/issues/7") + if err != nil || !reserved { + t.Fatalf("reserve issue task = %v, err %v", reserved, err) + } + reserved, err = store.ReserveIssueWatchTask(ctx, issueWatch.ID, "acme", "widget", 7, "https://github.com/acme/widget/issues/7") + if err != nil || reserved { + t.Fatalf("duplicate issue reservation = %v, err %v", reserved, err) + } + if err := store.AssignIssueWatchTaskID(ctx, issueWatch.ID, "acme", "widget", 7, "task-1"); err != nil { + t.Fatalf("assign issue task: %v", err) + } + + autoFix, autoMerge := true, true + options, err := store.UpdateTaskCIOptions(ctx, "task-1", TaskCIOptionsPatch{ + AutoFixEnabled: &autoFix, + AutoFixPromptOverride: stringPointer("fix it"), + }) + if err != nil || options == nil || options.AutoFixPromptOverride == nil { + t.Fatalf("update task CI options = %+v, err %v", options, err) + } + prOptions, err := store.UpdateTaskPRAutomationOptions(ctx, "task-1", "repo-1", 42, + TaskPRAutomationOptionsPatch{AutoMergeEnabled: &autoMerge}, false) + if err != nil || prOptions == nil || !prOptions.AutoMergeEnabled { + t.Fatalf("update task PR automation options = %+v, err %v", prOptions, err) + } + + flow := &AuthFlow{ + StateHash: "state-hash-postgres", + WorkspaceID: "ws-1", + UserID: "user-1", + AppRegistrationID: registration.ID, + Kind: AuthFlowKindPersonal, + PKCEVerifier: "verifier", + ExpectedWorkspaceSource: ConnectionSourceGitHubAppInstallation, + ExpectedWorkspaceGeneration: 2, + ExpectedInstallationID: &installationID, + ExpectedWorkspaceAppRegistrationID: registration.ID, + ExpectedPersonalGeneration: 1, + ExpiresAt: now.Add(time.Hour), + } + if err := store.CreateAuthFlow(ctx, flow); err != nil { + t.Fatalf("create auth flow: %v", err) + } + if consumed, err := store.ConsumeAuthFlow(ctx, flow.StateHash, registration.ID, flow.Kind, now); err != nil || consumed == nil || consumed.ConsumedAt == nil { + t.Fatalf("consume auth flow = %+v, err %v", consumed, err) + } + + stats, err := store.GetPRStats(ctx, &PRStatsRequest{WorkspaceID: "ws-1"}) + if err != nil || stats == nil || stats.TotalPRsCreated != 1 { + t.Fatalf("get PR stats = %+v, err %v", stats, err) + } + if err := store.DeleteReviewWatch(ctx, reviewWatch.ID); err != nil { + t.Fatalf("delete review watch: %v", err) + } + if err := store.DeleteIssueWatch(ctx, issueWatch.ID); err != nil { + t.Fatalf("delete issue watch: %v", err) + } + if err := store.DeleteUserConnection(ctx, "ws-1", "user-1"); err != nil { + t.Fatalf("delete personal GitHub connection: %v", err) + } + if err := store.UpsertUserConnection(ctx, userConnection); err != nil { + t.Fatalf("re-upsert personal GitHub connection: %v", err) + } + if err := store.DeleteUserConnectionsByWorkspace(ctx, "ws-1"); err != nil { + t.Fatalf("delete workspace GitHub connections: %v", err) + } +} + +func stringPointer(value string) *string { + return &value +} diff --git a/apps/backend/internal/github/store_task_cleanup.go b/apps/backend/internal/github/store_task_cleanup.go index 174ce92ac4..2e8dabb595 100644 --- a/apps/backend/internal/github/store_task_cleanup.go +++ b/apps/backend/internal/github/store_task_cleanup.go @@ -2,9 +2,9 @@ package github import ( "context" - "database/sql" - "errors" "fmt" + + dbutil "github.com/kandev/kandev/internal/db" ) var githubTaskOwnedTables = []string{ @@ -18,7 +18,7 @@ var githubTaskOwnedTables = []string{ // DeleteTaskPRsByTaskID removes every contribution association owned by a // hard-deleted task. It is safe to replay after a missed event. func (s *Store) DeleteTaskPRsByTaskID(ctx context.Context, taskID string) (int64, error) { - result, err := s.db.ExecContext(ctx, `DELETE FROM github_task_prs WHERE task_id = ?`, taskID) + result, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM github_task_prs WHERE task_id = ?`), taskID) if err != nil { return 0, err } @@ -36,7 +36,7 @@ func (s *Store) DeleteTaskOwnedStateByTaskID(ctx context.Context, taskID string) var deleted int64 for _, table := range githubTaskOwnedTables { - result, err := tx.ExecContext(ctx, `DELETE FROM `+table+` WHERE task_id = ?`, taskID) + result, err := tx.ExecContext(ctx, tx.Rebind(`DELETE FROM `+table+` WHERE task_id = ?`), taskID) if err != nil { return 0, fmt.Errorf("delete task-owned rows from %s: %w", table, err) } @@ -53,14 +53,13 @@ func (s *Store) DeleteTaskOwnedStateByTaskID(ctx context.Context, taskID string) } func (s *Store) healTaskOwnedOrphans() error { - var exists int - err := s.db.Get(&exists, `SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'tasks'`) - if errors.Is(err, sql.ErrNoRows) { - return nil - } + exists, err := dbutil.TableExists(s.db, "tasks") if err != nil { return fmt.Errorf("check tasks table for orphan sweep: %w", err) } + if !exists { + return nil + } tx, err := s.db.Beginx() if err != nil { @@ -68,7 +67,7 @@ func (s *Store) healTaskOwnedOrphans() error { } defer func() { _ = tx.Rollback() }() for _, table := range githubTaskOwnedTables { - if _, err := tx.Exec(`DELETE FROM ` + table + ` WHERE NOT EXISTS (SELECT 1 FROM tasks WHERE tasks.id = ` + table + `.task_id)`); err != nil { + if _, err := tx.Exec(tx.Rebind(`DELETE FROM ` + table + ` WHERE NOT EXISTS (SELECT 1 FROM tasks WHERE tasks.id = ` + table + `.task_id)`)); err != nil { return fmt.Errorf("remove orphaned %s: %w", table, err) } } diff --git a/apps/backend/internal/github/store_task_pr_ownership.go b/apps/backend/internal/github/store_task_pr_ownership.go index f1d985d2c2..19d85dd425 100644 --- a/apps/backend/internal/github/store_task_pr_ownership.go +++ b/apps/backend/internal/github/store_task_pr_ownership.go @@ -87,11 +87,11 @@ func findTaskPRMemberTx( ctx context.Context, tx *sqlx.Tx, memberTaskID, repositoryID string, prNumber int, ) (string, string, bool, error) { var memberID, source string - err := tx.QueryRowxContext(ctx, ` + err := tx.QueryRowxContext(ctx, tx.Rebind(` SELECT id, source FROM github_task_prs WHERE task_id = ? AND repository_id = ? AND pr_number = ? AND detached_at IS NULL - LIMIT 1`, memberTaskID, repositoryID, prNumber).Scan(&memberID, &source) + LIMIT 1`), memberTaskID, repositoryID, prNumber).Scan(&memberID, &source) if errors.Is(err, sql.ErrNoRows) { return "", "", false, nil } @@ -117,22 +117,22 @@ func findTaskPROwnerStateTx( ctx context.Context, tx *sqlx.Tx, ownerTaskID, repositoryID string, prNumber int, ) (taskPROwnerState, error) { var ownerID string - err := tx.QueryRowxContext(ctx, ` + err := tx.QueryRowxContext(ctx, tx.Rebind(` SELECT id FROM github_task_prs WHERE task_id = ? AND repository_id = ? AND pr_number = ? AND detached_at IS NULL - LIMIT 1`, ownerTaskID, repositoryID, prNumber).Scan(&ownerID) + LIMIT 1`), ownerTaskID, repositoryID, prNumber).Scan(&ownerID) if err == nil { return taskPROwnerActive, nil } if !errors.Is(err, sql.ErrNoRows) { return taskPROwnerAbsent, fmt.Errorf("load owner task PR: %w", err) } - err = tx.QueryRowxContext(ctx, ` + err = tx.QueryRowxContext(ctx, tx.Rebind(` SELECT id FROM github_task_prs WHERE task_id = ? AND repository_id = ? AND pr_number = ? - LIMIT 1`, ownerTaskID, repositoryID, prNumber).Scan(&ownerID) + LIMIT 1`), ownerTaskID, repositoryID, prNumber).Scan(&ownerID) if err == nil { return taskPROwnerDetached, nil } @@ -148,11 +148,11 @@ func moveTaskPROwnershipTx( if err := copyTaskPROwnershipStateTx(ctx, tx, memberTaskID, ownerTaskID, repositoryID, prNumber); err != nil { return err } - result, err := tx.ExecContext(ctx, ` + result, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_prs SET task_id = ?, updated_at = ? WHERE id = ? AND task_id = ? AND repository_id = ? AND pr_number = ? AND detached_at IS NULL`, - ownerTaskID, time.Now().UTC(), memberID, memberTaskID, repositoryID, prNumber) + ), ownerTaskID, time.Now().UTC(), memberID, memberTaskID, repositoryID, prNumber) if err != nil { return fmt.Errorf("move task PR to owner: %w", err) } @@ -167,21 +167,21 @@ func moveTaskPROwnershipTx( func detachTaskPROwnershipRowTx( ctx context.Context, tx *sqlx.Tx, memberID, memberTaskID, repositoryID string, prNumber int, ) error { - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE github_task_prs SET detached_at = ?, updated_at = ? - WHERE id = ? AND task_id = ? AND repository_id = ? AND pr_number = ? AND detached_at IS NULL`, + WHERE id = ? AND task_id = ? AND repository_id = ? AND pr_number = ? AND detached_at IS NULL`), time.Now().UTC(), time.Now().UTC(), memberID, memberTaskID, repositoryID, prNumber); err != nil { return fmt.Errorf("detach duplicate task PR: %w", err) } - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` DELETE FROM github_task_pr_automation_options - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, memberTaskID, repositoryID, prNumber); err != nil { + WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), memberTaskID, repositoryID, prNumber); err != nil { return fmt.Errorf("remove duplicate task PR automation options: %w", err) } - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` DELETE FROM github_task_ci_pr_state - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, memberTaskID, repositoryID, prNumber); err != nil { + WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), memberTaskID, repositoryID, prNumber); err != nil { return fmt.Errorf("remove duplicate task PR automation state: %w", err) } return nil @@ -190,20 +190,21 @@ func detachTaskPROwnershipRowTx( func copyTaskPROwnershipStateTx( ctx context.Context, tx *sqlx.Tx, memberTaskID, ownerTaskID, repositoryID string, prNumber int, ) error { - if _, err := tx.ExecContext(ctx, ` - INSERT OR IGNORE INTO github_task_pr_automation_options ( + if _, err := tx.ExecContext(ctx, tx.Rebind(` + INSERT INTO github_task_pr_automation_options ( task_id, repository_id, pr_number, auto_fix_enabled, auto_merge_enabled, prompt_on_review_requested, prompt_on_merged, prompt_on_closed, created_at, updated_at ) SELECT ?, repository_id, pr_number, auto_fix_enabled, auto_merge_enabled, prompt_on_review_requested, prompt_on_merged, prompt_on_closed, created_at, updated_at FROM github_task_pr_automation_options - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, + WHERE task_id = ? AND repository_id = ? AND pr_number = ? + ON CONFLICT(task_id, repository_id, pr_number) DO NOTHING`), ownerTaskID, memberTaskID, repositoryID, prNumber); err != nil { return fmt.Errorf("copy task PR automation options: %w", err) } - if _, err := tx.ExecContext(ctx, ` - INSERT OR IGNORE INTO github_task_ci_pr_state ( + if _, err := tx.ExecContext(ctx, tx.Rebind(` + INSERT INTO github_task_ci_pr_state ( task_id, repository_id, pr_number, last_fix_signature, last_fix_checkpoint_json, last_fix_enqueued_at, last_fix_session_id, auto_fix_round_count, auto_fix_exhausted_at, last_merge_signature, last_merge_attempt_at, last_merge_result, merge_retry_pending, @@ -220,7 +221,8 @@ func copyTaskPROwnershipStateTx( last_lifecycle_event, last_lifecycle_prompt_at, last_lifecycle_session_id, last_error, last_error_kind, created_at, updated_at FROM github_task_ci_pr_state - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, + WHERE task_id = ? AND repository_id = ? AND pr_number = ? + ON CONFLICT(task_id, repository_id, pr_number) DO NOTHING`), ownerTaskID, memberTaskID, repositoryID, prNumber); err != nil { return fmt.Errorf("copy task PR automation state: %w", err) } @@ -230,14 +232,14 @@ func copyTaskPROwnershipStateTx( func moveTaskPROwnershipStateTx( ctx context.Context, tx *sqlx.Tx, memberTaskID, ownerTaskID, repositoryID string, prNumber int, ) error { - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` DELETE FROM github_task_pr_automation_options - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, memberTaskID, repositoryID, prNumber); err != nil { + WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), memberTaskID, repositoryID, prNumber); err != nil { return fmt.Errorf("remove moved task PR automation options: %w", err) } - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` DELETE FROM github_task_ci_pr_state - WHERE task_id = ? AND repository_id = ? AND pr_number = ?`, memberTaskID, repositoryID, prNumber); err != nil { + WHERE task_id = ? AND repository_id = ? AND pr_number = ?`), memberTaskID, repositoryID, prNumber); err != nil { return fmt.Errorf("remove moved task PR automation state: %w", err) } return nil diff --git a/apps/backend/internal/gitlab/store.go b/apps/backend/internal/gitlab/store.go index e1ae71b958..429e1d9d51 100644 --- a/apps/backend/internal/gitlab/store.go +++ b/apps/backend/internal/gitlab/store.go @@ -11,6 +11,9 @@ import ( "github.com/google/uuid" "github.com/jmoiron/sqlx" + + dbutil "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/db/dialect" ) // Store backs the task↔MR association used by the topbar / review surface. @@ -214,7 +217,7 @@ const createTablesSQL = ` ` func (s *Store) createTables() error { - if _, err := s.db.Exec(createTablesSQL); err != nil { + if _, err := s.db.Exec(gitlabSchemaSQLForDriver(createTablesSQL, s.db.DriverName())); err != nil { return err } if err := s.createMRAutomationTables(); err != nil { @@ -285,10 +288,12 @@ func (s *Store) ensureMRWatchIndexes() error { // per branch on the same repository (multi-branch tasks) instead of // colliding on the second branch's insert. SQLite can't ALTER TABLE DROP // CONSTRAINT, so this uses the same copy-and-rename rebuild as -// github.Store.migratePRTablesForMultiRepo. Idempotent: only runs when the -// legacy constraint string is found in sqlite_master, so fresh DBs and -// already-migrated DBs are no-ops. +// github.Store.migratePRTablesForMultiRepo. Both paths are idempotent: SQLite +// checks the stored table DDL, while PostgreSQL checks its unique constraints. func (s *Store) migrateMRWatchUniqueKey() error { + if dialect.IsPostgres(s.db.DriverName()) { + return s.migratePostgresMRWatchUniqueKey() + } return s.rebuildIfHasLegacyConstraint( "gitlab_mr_watches", "UNIQUE(session_id, repository_id)\n", @@ -320,6 +325,106 @@ func (s *Store) migrateMRWatchUniqueKey() error { ) } +// migratePostgresMRWatchUniqueKey replaces the legacy two-column unique +// constraint with the branch-aware key. PostgreSQL can alter the constraint +// directly, so it does not need the SQLite table rebuild used above. +func (s *Store) migratePostgresMRWatchUniqueKey() error { + tx, err := s.db.BeginTxx(context.Background(), nil) + if err != nil { + return err + } + defer func() { _ = tx.Rollback() }() + + legacyConstraint, err := postgresMRWatchUniqueConstraint(tx, "session_id", "repository_id") + if err != nil { + return err + } + if legacyConstraint == "" { + return tx.Commit() + } + + if _, err := tx.Exec( + `ALTER TABLE gitlab_mr_watches DROP CONSTRAINT ` + quotePostgresIdentifier(legacyConstraint), + ); err != nil { + return fmt.Errorf("drop legacy gitlab MR watch constraint: %w", err) + } + + branchConstraint, err := postgresMRWatchUniqueConstraint(tx, "session_id", "repository_id", "branch") + if err != nil { + return err + } + if branchConstraint == "" { + if _, err := tx.Exec(` + ALTER TABLE gitlab_mr_watches + ADD CONSTRAINT gitlab_mr_watches_session_repository_branch_key + UNIQUE (session_id, repository_id, branch)`); err != nil { + return fmt.Errorf("add branch-aware gitlab MR watch constraint: %w", err) + } + } + return tx.Commit() +} + +// postgresMRWatchUniqueConstraint returns the name of an exact-column unique +// constraint on gitlab_mr_watches. The catalog query handles PostgreSQL's +// generated names, which vary with the table's creation history. +func postgresMRWatchUniqueConstraint(tx *sqlx.Tx, columns ...string) (string, error) { + rows, err := tx.Query(` + SELECT tc.constraint_name, kcu.column_name + FROM information_schema.table_constraints tc + JOIN information_schema.key_column_usage kcu + ON kcu.constraint_schema = tc.constraint_schema + AND kcu.constraint_name = tc.constraint_name + AND kcu.table_schema = tc.table_schema + AND kcu.table_name = tc.table_name + WHERE tc.table_schema = current_schema() + AND tc.table_name = 'gitlab_mr_watches' + AND tc.constraint_type = 'UNIQUE' + ORDER BY tc.constraint_name, kcu.ordinal_position`) + if err != nil { + return "", err + } + defer func() { _ = rows.Close() }() + + constraintColumns := make(map[string][]string) + for rows.Next() { + var constraintName, columnName string + if err := rows.Scan(&constraintName, &columnName); err != nil { + return "", err + } + constraintColumns[constraintName] = append(constraintColumns[constraintName], columnName) + } + if err := rows.Err(); err != nil { + return "", err + } + for constraintName, constraintColumns := range constraintColumns { + if sameColumnSet(constraintColumns, columns) { + return constraintName, nil + } + } + return "", nil +} + +func sameColumnSet(actual, expected []string) bool { + if len(actual) != len(expected) { + return false + } + seen := make(map[string]struct{}, len(expected)) + for _, column := range expected { + seen[column] = struct{}{} + } + for _, column := range actual { + if _, ok := seen[column]; !ok { + return false + } + delete(seen, column) + } + return len(seen) == 0 +} + +func quotePostgresIdentifier(identifier string) string { + return `"` + strings.ReplaceAll(identifier, `"`, `""`) + `"` +} + // rebuildIfHasLegacyConstraint checks the table's stored CREATE statement in // sqlite_master for the literal legacyConstraint substring; if present, runs // the table rebuild (create new, copy data, drop old, rename) inside a @@ -392,7 +497,8 @@ func (s *Store) migrateWatchColumns() error { if _, ok := existing[column.name]; ok { continue } - if _, err := s.db.Exec(fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s %s", table, column.name, column.ddl)); err != nil { + statement := fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s %s", table, column.name, column.ddl) + if _, err := s.db.Exec(gitlabSchemaSQLForDriver(statement, s.db.DriverName())); err != nil { return fmt.Errorf("migrate %s.%s: %w", table, column.name, err) } } @@ -403,7 +509,8 @@ func (s *Store) migrateWatchColumns() error { return err } if _, ok := existing["generation"]; !ok { - if _, err := s.db.Exec(fmt.Sprintf("ALTER TABLE %s ADD COLUMN generation INTEGER NOT NULL DEFAULT 1", table)); err != nil { + statement := fmt.Sprintf("ALTER TABLE %s ADD COLUMN generation INTEGER NOT NULL DEFAULT 1", table) + if _, err := s.db.Exec(gitlabSchemaSQLForDriver(statement, s.db.DriverName())); err != nil { return fmt.Errorf("migrate %s.generation: %w", table, err) } } @@ -412,22 +519,27 @@ func (s *Store) migrateWatchColumns() error { } func (s *Store) tableColumns(table string) (map[string]struct{}, error) { - rows, err := s.db.Query(fmt.Sprintf("PRAGMA table_info(%s)", table)) + columns, err := dbutil.TableColumns(s.db, table) if err != nil { return nil, err } - defer func() { _ = rows.Close() }() - columns := make(map[string]struct{}) - for rows.Next() { - var cid, notNull, primaryKey int - var name, columnType string - var defaultValue sql.NullString - if err := rows.Scan(&cid, &name, &columnType, ¬Null, &defaultValue, &primaryKey); err != nil { - return nil, err - } - columns[name] = struct{}{} + result := make(map[string]struct{}, len(columns)) + for name := range columns { + result[name] = struct{}{} } - return columns, rows.Err() + return result, nil +} + +func gitlabSchemaSQLForDriver(schema, driver string) string { + schema = strings.ReplaceAll(schema, "TIMESTAMP", dialect.TimestampType(driver)) + schema = strings.ReplaceAll(schema, "DATETIME", dialect.TimestampType(driver)) + if dialect.IsPostgres(driver) { + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 1", "BOOLEAN DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 0", "BOOLEAN DEFAULT FALSE") + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 1", "BOOLEAN NOT NULL DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 0", "BOOLEAN NOT NULL DEFAULT FALSE") + } + return schema } // UpsertMentionScope explicitly binds one workspace to a GitLab host and @@ -441,13 +553,13 @@ func (s *Store) UpsertMentionScope(ctx context.Context, scope *MentionScope) err return fmt.Errorf("marshal gitlab mention projects: %w", err) } now := time.Now().UTC() - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO gitlab_mention_scopes (workspace_id, host, projects_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(workspace_id) DO UPDATE SET host = excluded.host, projects_json = excluded.projects_json, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), scope.WorkspaceID, scope.Host, string(projects), now, now) return err } @@ -460,10 +572,10 @@ func (s *Store) GetMentionScope(ctx context.Context, workspaceID string) (*Menti Host string `db:"host"` Projects string `db:"projects_json"` } - err := s.ro.GetContext(ctx, &row, ` + err := s.ro.GetContext(ctx, &row, s.ro.Rebind(` SELECT workspace_id, host, projects_json FROM gitlab_mention_scopes - WHERE workspace_id = ?`, workspaceID) + WHERE workspace_id = ?`), workspaceID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -523,7 +635,7 @@ func (s *Store) UpsertTaskMR(ctx context.Context, tm *TaskMR) error { ) VALUES ( :id, :task_id, :repository_id, :host, :project_path, :mr_iid, :mr_url, :mr_title, :head_branch, :base_branch, :author_username, :state, :approval_state, :pipeline_state, - :merge_status, :draft, :approval_count, :required_approvals, + :merge_status, CASE WHEN :draft THEN 1 ELSE 0 END, :approval_count, :required_approvals, :pipeline_jobs_total, :pipeline_jobs_pass, :detailed_merge_status, :reviewer_count, :unapproved_reviewers, :unresolved_discussions, :created_at, :merged_at, :closed_at, :last_synced_at, :updated_at @@ -569,8 +681,8 @@ func (s *Store) UpsertTaskMR(ctx context.Context, tm *TaskMR) error { // comment there for why the general lifecycle sync must never touch this // column. func (s *Store) UpdateTaskMRUnresolvedDiscussions(ctx context.Context, id string, count int) error { - _, err := s.db.ExecContext(ctx, - `UPDATE gitlab_task_mrs SET unresolved_discussions = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE gitlab_task_mrs SET unresolved_discussions = ?, updated_at = ? WHERE id = ?`), count, time.Now().UTC(), id) return err } @@ -581,10 +693,10 @@ func (s *Store) UpdateTaskMRUnresolvedDiscussions(ctx context.Context, id string // actually changed anything worth publishing. func (s *Store) GetTaskMR(ctx context.Context, taskID, repositoryID, projectPath string, iid int) (*TaskMR, error) { var tm TaskMR - err := s.ro.GetContext(ctx, &tm, ` + err := s.ro.GetContext(ctx, &tm, s.ro.Rebind(` SELECT `+taskMRSelectCols+` FROM gitlab_task_mrs WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ? - LIMIT 1`, taskID, repositoryID, projectPath, iid) + LIMIT 1`), taskID, repositoryID, projectPath, iid) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -598,8 +710,8 @@ func (s *Store) GetTaskMR(ctx context.Context, taskID, repositoryID, projectPath // by source-aware detach cleanup before the row is removed. func (s *Store) GetTaskMRByID(ctx context.Context, id string) (*TaskMR, error) { var tm TaskMR - err := s.ro.GetContext(ctx, &tm, ` - SELECT `+taskMRSelectCols+` FROM gitlab_task_mrs WHERE id = ? LIMIT 1`, id) + err := s.ro.GetContext(ctx, &tm, s.ro.Rebind( + `SELECT `+taskMRSelectCols+` FROM gitlab_task_mrs WHERE id = ? LIMIT 1`), id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -612,9 +724,9 @@ func (s *Store) GetTaskMRByID(ctx context.Context, id string) (*TaskMR, error) { // ListTaskMRsByTask returns every MR association for a task, oldest first. func (s *Store) ListTaskMRsByTask(ctx context.Context, taskID string) ([]*TaskMR, error) { var mrs []TaskMR - if err := s.ro.SelectContext(ctx, &mrs, + if err := s.ro.SelectContext(ctx, &mrs, s.ro.Rebind( `SELECT `+taskMRSelectCols+` FROM gitlab_task_mrs - WHERE task_id = ? ORDER BY created_at ASC`, taskID); err != nil { + WHERE task_id = ? ORDER BY created_at ASC`), taskID); err != nil { return nil, err } out := make([]*TaskMR, 0, len(mrs)) @@ -629,11 +741,11 @@ func (s *Store) ListTaskMRsByTask(ctx context.Context, taskID string) ([]*TaskMR // GitLab MRs. func (s *Store) ListTaskMRsByWorkspaceID(ctx context.Context, workspaceID string) (map[string][]*TaskMR, error) { var mrs []TaskMR - if err := s.ro.SelectContext(ctx, &mrs, + if err := s.ro.SelectContext(ctx, &mrs, s.ro.Rebind( `SELECT `+taskMRSelectColsQualified+` FROM gitlab_task_mrs gtm INNER JOIN tasks t ON gtm.task_id = t.id WHERE t.workspace_id = ? - ORDER BY gtm.created_at ASC`, workspaceID); err != nil { + ORDER BY gtm.created_at ASC`), workspaceID); err != nil { return nil, err } out := make(map[string][]*TaskMR) @@ -666,26 +778,26 @@ func (s *Store) DeleteTaskMR(ctx context.Context, id string) error { ProjectPath string `db:"project_path"` MRIID int `db:"mr_iid"` } - err = tx.GetContext(ctx, &mr, - `SELECT task_id, repository_id, project_path, mr_iid FROM gitlab_task_mrs WHERE id = ?`, id) + err = tx.GetContext(ctx, &mr, tx.Rebind( + `SELECT task_id, repository_id, project_path, mr_iid FROM gitlab_task_mrs WHERE id = ?`), id) if errors.Is(err, sql.ErrNoRows) { return nil } if err != nil { return err } - if _, err := tx.ExecContext(ctx, + if _, err := tx.ExecContext(ctx, tx.Rebind( `DELETE FROM gitlab_task_mr_state WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, - mr.TaskID, mr.RepositoryID, mr.ProjectPath, mr.MRIID); err != nil { + ), mr.TaskID, mr.RepositoryID, mr.ProjectPath, mr.MRIID); err != nil { return err } - if _, err := tx.ExecContext(ctx, + if _, err := tx.ExecContext(ctx, tx.Rebind( `DELETE FROM gitlab_task_mr_automation_options WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, - mr.TaskID, mr.RepositoryID, mr.ProjectPath, mr.MRIID); err != nil { + ), mr.TaskID, mr.RepositoryID, mr.ProjectPath, mr.MRIID); err != nil { return err } - if _, err := tx.ExecContext(ctx, `DELETE FROM gitlab_task_mrs WHERE id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(`DELETE FROM gitlab_task_mrs WHERE id = ?`), id); err != nil { return err } return tx.Commit() diff --git a/apps/backend/internal/gitlab/store_config.go b/apps/backend/internal/gitlab/store_config.go index 0e1aa7912e..50f24fdf39 100644 --- a/apps/backend/internal/gitlab/store_config.go +++ b/apps/backend/internal/gitlab/store_config.go @@ -12,6 +12,7 @@ import ( type configExecer interface { ExecContext(context.Context, string, ...any) (sql.Result, error) QueryRowxContext(context.Context, string, ...any) *sqlx.Row + Rebind(string) string } const configSelectColumns = `workspace_id, host, auth_method, username, @@ -20,8 +21,8 @@ const configSelectColumns = `workspace_id, host, auth_method, username, // GetConfigForWorkspace returns one workspace's config or nil when absent. func (s *Store) GetConfigForWorkspace(ctx context.Context, workspaceID string) (*GitLabConfig, error) { var cfg GitLabConfig - err := s.ro.GetContext(ctx, &cfg, `SELECT `+configSelectColumns+` - FROM gitlab_configs WHERE workspace_id = ?`, workspaceID) + err := s.ro.GetContext(ctx, &cfg, s.ro.Rebind(`SELECT `+configSelectColumns+` + FROM gitlab_configs WHERE workspace_id = ?`), workspaceID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -43,7 +44,7 @@ func upsertConfigForWorkspace(ctx context.Context, execer configExecer, workspac } cfg.WorkspaceID = workspaceID cfg.UpdatedAt = now - err := execer.QueryRowxContext(ctx, ` + err := execer.QueryRowxContext(ctx, execer.Rebind(` INSERT INTO gitlab_configs ( workspace_id, host, auth_method, username, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?) @@ -53,7 +54,7 @@ func upsertConfigForWorkspace(ctx context.Context, execer configExecer, workspac username = excluded.username, updated_at = excluded.updated_at, revision = gitlab_configs.revision + 1 - RETURNING revision`, + RETURNING revision`), workspaceID, cfg.Host, cfg.AuthMethod, cfg.Username, cfg.CreatedAt, cfg.UpdatedAt). Scan(&cfg.Revision) return err @@ -85,7 +86,7 @@ func (s *Store) SaveConfigForWorkspace(ctx context.Context, workspaceID string, // DeleteConfigForWorkspace removes only the selected workspace connection. func (s *Store) DeleteConfigForWorkspace(ctx context.Context, workspaceID string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM gitlab_configs WHERE workspace_id = ?`, workspaceID) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM gitlab_configs WHERE workspace_id = ?`), workspaceID) return err } @@ -103,10 +104,10 @@ func (s *Store) UpdateConfigHealthForRevision(ctx context.Context, workspaceID, } func updateConfigHealthForRevision(ctx context.Context, execer configExecer, workspaceID, username string, ok bool, errMsg string, checkedAt time.Time, revision int64) (bool, error) { - result, err := execer.ExecContext(ctx, ` + result, err := execer.ExecContext(ctx, execer.Rebind(` UPDATE gitlab_configs - SET username = ?, last_ok = ?, last_error = ?, last_checked_at = ?, updated_at = ? - WHERE workspace_id = ? AND revision = ?`, + SET username = ?, last_ok = CASE WHEN ? THEN 1 ELSE 0 END, last_error = ?, last_checked_at = ?, updated_at = ? + WHERE workspace_id = ? AND revision = ?`), username, ok, errMsg, checkedAt, checkedAt, workspaceID, revision) if err != nil { return false, err @@ -121,11 +122,11 @@ func (s *Store) RestoreConfigForWorkspace(ctx context.Context, workspaceID strin if cfg == nil { return s.DeleteConfigForWorkspace(ctx, workspaceID) } - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO gitlab_configs ( workspace_id, host, auth_method, username, last_ok, last_error, last_checked_at, revision, created_at, updated_at - ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ) VALUES (?, ?, ?, ?, CASE WHEN ? THEN 1 ELSE 0 END, ?, ?, ?, ?, ?) ON CONFLICT(workspace_id) DO UPDATE SET host = excluded.host, auth_method = excluded.auth_method, @@ -135,7 +136,7 @@ func (s *Store) RestoreConfigForWorkspace(ctx context.Context, workspaceID strin last_checked_at = excluded.last_checked_at, revision = excluded.revision, created_at = excluded.created_at, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), workspaceID, cfg.Host, cfg.AuthMethod, cfg.Username, cfg.LastOK, cfg.LastError, cfg.LastCheckedAt, cfg.Revision, cfg.CreatedAt, cfg.UpdatedAt) return err @@ -145,7 +146,7 @@ func (s *Store) RestoreConfigForWorkspace(ctx context.Context, workspaceID strin // operation. func (s *Store) WorkspaceIDForTask(ctx context.Context, taskID string) (string, error) { var workspaceID string - err := s.ro.GetContext(ctx, &workspaceID, `SELECT workspace_id FROM tasks WHERE id = ?`, taskID) + err := s.ro.GetContext(ctx, &workspaceID, s.ro.Rebind(`SELECT workspace_id FROM tasks WHERE id = ?`), taskID) if errors.Is(err, sql.ErrNoRows) { return "", ErrNotConfigured } diff --git a/apps/backend/internal/gitlab/store_e2e_reset.go b/apps/backend/internal/gitlab/store_e2e_reset.go index 47907d6538..44b3fd31bf 100644 --- a/apps/backend/internal/gitlab/store_e2e_reset.go +++ b/apps/backend/internal/gitlab/store_e2e_reset.go @@ -26,7 +26,7 @@ func (s *Store) ResetWorkspaceE2E(ctx context.Context, workspaceID string) (E2ER (SELECT id FROM gitlab_issue_watches WHERE workspace_id = ?)`, } for _, query := range queries { - if _, err := tx.ExecContext(ctx, query, workspaceID); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(query), workspaceID); err != nil { return E2EResetResult{}, err } } @@ -40,13 +40,13 @@ func (s *Store) ResetWorkspaceE2E(ctx context.Context, workspaceID string) (E2ER return E2EResetResult{}, err } - reviewResult, err := tx.ExecContext(ctx, - `DELETE FROM gitlab_review_watches WHERE workspace_id = ?`, workspaceID) + reviewResult, err := tx.ExecContext(ctx, tx.Rebind( + `DELETE FROM gitlab_review_watches WHERE workspace_id = ?`), workspaceID) if err != nil { return E2EResetResult{}, err } - issueResult, err := tx.ExecContext(ctx, - `DELETE FROM gitlab_issue_watches WHERE workspace_id = ?`, workspaceID) + issueResult, err := tx.ExecContext(ctx, tx.Rebind( + `DELETE FROM gitlab_issue_watches WHERE workspace_id = ?`), workspaceID) if err != nil { return E2EResetResult{}, err } @@ -59,7 +59,7 @@ func (s *Store) ResetWorkspaceE2E(ctx context.Context, workspaceID string) (E2ER (SELECT id FROM tasks WHERE workspace_id = ?)`, } for _, query := range workspaceDeletes { - if _, err := tx.ExecContext(ctx, query, workspaceID); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(query), workspaceID); err != nil { return E2EResetResult{}, err } } diff --git a/apps/backend/internal/gitlab/store_mr_automation.go b/apps/backend/internal/gitlab/store_mr_automation.go index 6770492245..e49082b9ef 100644 --- a/apps/backend/internal/gitlab/store_mr_automation.go +++ b/apps/backend/internal/gitlab/store_mr_automation.go @@ -86,7 +86,7 @@ const createMRAutomationTablesSQL = ` // migrateMRAutomationAutomationColumns (called from Store.createTables // after this) adds them via idempotent ALTER TABLE. func (s *Store) createMRAutomationTables() error { - _, err := s.db.Exec(createMRAutomationTablesSQL) + _, err := s.db.Exec(gitlabSchemaSQLForDriver(createMRAutomationTablesSQL, s.db.DriverName())) return err } @@ -181,7 +181,7 @@ func (s *Store) fanOutMROptionsToMRScope(row legacyMROptionsRow) error { } defer func() { _ = tx.Rollback() }() now := time.Now().UTC() - if _, err := tx.Exec(` + if _, err := tx.Exec(tx.Rebind(` INSERT INTO gitlab_task_mr_automation_options ( task_id, repository_id, project_path, mr_iid, auto_fix_enabled, auto_merge_enabled, prompt_on_review_requested, prompt_on_merged, prompt_on_closed, created_at, updated_at @@ -189,13 +189,13 @@ func (s *Store) fanOutMROptionsToMRScope(row legacyMROptionsRow) error { SELECT task_id, repository_id, project_path, mr_iid, ?, ?, ?, ?, ?, ?, ? FROM gitlab_task_mrs WHERE task_id = ? - ON CONFLICT(task_id, repository_id, project_path, mr_iid) DO NOTHING`, + ON CONFLICT(task_id, repository_id, project_path, mr_iid) DO NOTHING`), row.autoFix, row.autoMerge, row.promptReview, row.promptMerged, row.promptClosed, now, now, row.taskID); err != nil { return fmt.Errorf("fan out task MR options for %s: %w", row.taskID, err) } - if _, err := tx.Exec( - `UPDATE gitlab_task_mr_options SET mr_scope_migrated_at = ? WHERE task_id = ?`, now, row.taskID, + if _, err := tx.Exec(tx.Rebind( + `UPDATE gitlab_task_mr_options SET mr_scope_migrated_at = ? WHERE task_id = ?`), now, row.taskID, ); err != nil { return fmt.Errorf("stamp mr_scope_migrated_at for %s: %w", row.taskID, err) } @@ -211,7 +211,8 @@ func addMissingColumns(s *Store, table string, columns []struct{ name, ddl strin if _, ok := existing[column.name]; ok { continue } - if _, err := s.db.Exec(fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s %s", table, column.name, column.ddl)); err != nil { + statement := fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s %s", table, column.name, column.ddl) + if _, err := s.db.Exec(gitlabSchemaSQLForDriver(statement, s.db.DriverName())); err != nil { return fmt.Errorf("migrate %s.%s: %w", table, column.name, err) } } @@ -223,6 +224,7 @@ func addMissingColumns(s *Store, table string, columns []struct{ name, ddl strin // existing ResetWorkspaceE2E transaction. type execContext interface { ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) + Rebind(query string) string } const mrAutomationOptionsSelectCols = `task_id, automation_revision, auto_fix_enabled, auto_merge_enabled, auto_fix_prompt_override, @@ -233,9 +235,9 @@ const mrAutomationOptionsSelectCols = `task_id, automation_revision, auto_fix_en // implicit all-false default when no row has been persisted yet (AC1). func (s *Store) GetTaskMRAutomationOptions(ctx context.Context, taskID string) (*TaskMRAutomationOptions, error) { var row TaskMRAutomationOptions - err := s.ro.GetContext(ctx, &row, ` + err := s.ro.GetContext(ctx, &row, s.ro.Rebind(` SELECT `+mrAutomationOptionsSelectCols+` - FROM gitlab_task_mr_options WHERE task_id = ?`, taskID) + FROM gitlab_task_mr_options WHERE task_id = ?`), taskID) if errors.Is(err, sql.ErrNoRows) { return &TaskMRAutomationOptions{TaskID: taskID}, nil } @@ -319,16 +321,16 @@ func updateTaskMRAutomationOptionsTx( ctx context.Context, tx *sqlx.Tx, taskID string, patch TaskMRAutomationPatch, reviewerUsername *string, ) error { now := time.Now().UTC() - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO gitlab_task_mr_options (task_id, created_at, updated_at) VALUES (?, ?, ?) - ON CONFLICT(task_id) DO NOTHING`, taskID, now, now); err != nil { + ON CONFLICT(task_id) DO NOTHING`), taskID, now, now); err != nil { return err } var previous TaskMRAutomationOptions - if err := tx.GetContext(ctx, &previous, + if err := tx.GetContext(ctx, &previous, tx.Rebind( `SELECT `+mrAutomationOptionsSelectCols+` - FROM gitlab_task_mr_options WHERE task_id = ?`, taskID); err != nil { + FROM gitlab_task_mr_options WHERE task_id = ?`), taskID); err != nil { return err } @@ -339,13 +341,13 @@ func updateTaskMRAutomationOptionsTx( if reviewerSet { reviewerValue = *reviewerUsername } - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE gitlab_task_mr_options SET auto_fix_prompt_override = CASE WHEN ? THEN ? ELSE auto_fix_prompt_override END, review_reviewer_username = CASE WHEN ? THEN ? ELSE review_reviewer_username END, automation_revision = automation_revision + 1, updated_at = ? - WHERE task_id = ?`, + WHERE task_id = ?`), promptSet, promptValue, reviewerSet, reviewerValue, now, taskID); err != nil { return err } @@ -371,10 +373,10 @@ func (s *Store) GetTaskMRAutomationOptionsForMR( ctx context.Context, taskID string, id MRIdentity, ) (*TaskMRAutomationOptionsForMR, error) { var row TaskMRAutomationOptionsForMR - err := s.ro.GetContext(ctx, &row, ` + err := s.ro.GetContext(ctx, &row, s.ro.Rebind(` SELECT `+mrAutomationSwitchSelectCols+` FROM gitlab_task_mr_automation_options - WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, + WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`), taskID, id.RepositoryID, id.ProjectPath, id.MRIID) if errors.Is(err, sql.ErrNoRows) { return &TaskMRAutomationOptionsForMR{ @@ -391,10 +393,10 @@ func (s *Store) GetTaskMRAutomationOptionsForMR( // ListTaskMRAutomationOptions returns every stored per-MR switch row for a task. func (s *Store) ListTaskMRAutomationOptions(ctx context.Context, taskID string) ([]*TaskMRAutomationOptionsForMR, error) { var rows []TaskMRAutomationOptionsForMR - if err := s.ro.SelectContext(ctx, &rows, ` + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind(` SELECT `+mrAutomationSwitchSelectCols+` FROM gitlab_task_mr_automation_options - WHERE task_id = ? ORDER BY project_path ASC, mr_iid ASC`, taskID); err != nil { + WHERE task_id = ? ORDER BY project_path ASC, mr_iid ASC`), taskID); err != nil { return nil, err } out := make([]*TaskMRAutomationOptionsForMR, 0, len(rows)) @@ -472,23 +474,23 @@ func applyMRSwitchPatchTx( if err := ensureTaskMRLinkTx(ctx, tx, taskID, id); err != nil { return err } - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` INSERT INTO gitlab_task_mr_automation_options ( task_id, repository_id, project_path, mr_iid, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?) - ON CONFLICT(task_id, repository_id, project_path, mr_iid) DO NOTHING`, + ON CONFLICT(task_id, repository_id, project_path, mr_iid) DO NOTHING`), taskID, id.RepositoryID, id.ProjectPath, id.MRIID, now, now); err != nil { return err } var previous TaskMRAutomationOptionsForMR - if err := tx.GetContext(ctx, &previous, ` + if err := tx.GetContext(ctx, &previous, tx.Rebind(` SELECT `+mrAutomationSwitchSelectCols+` FROM gitlab_task_mr_automation_options - WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, + WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`), taskID, id.RepositoryID, id.ProjectPath, id.MRIID); err != nil { return err } - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE gitlab_task_mr_automation_options SET auto_fix_enabled = CASE WHEN ? THEN ? ELSE auto_fix_enabled END, auto_merge_enabled = CASE WHEN ? THEN ? ELSE auto_merge_enabled END, @@ -496,7 +498,7 @@ func applyMRSwitchPatchTx( prompt_on_merged = CASE WHEN ? THEN ? ELSE prompt_on_merged END, prompt_on_closed = CASE WHEN ? THEN ? ELSE prompt_on_closed END, updated_at = ? - WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, + WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`), fields.autoFixSet, fields.autoFixValue, fields.autoMergeSet, fields.autoMergeValue, fields.reviewSet, fields.reviewValue, fields.mergedSet, fields.mergedValue, fields.closedSet, fields.closedValue, @@ -513,9 +515,9 @@ func ensureTaskMRLinkTx(ctx context.Context, tx *sqlx.Tx, taskID string, id MRId // The no-op UPDATE takes a write lock on the association row and is portable // across PostgreSQL and SQLite. The unlink transaction must wait until this // transaction commits, then removes the association and its options. - result, err := tx.ExecContext(ctx, ` + result, err := tx.ExecContext(ctx, tx.Rebind(` UPDATE gitlab_task_mrs SET updated_at = updated_at - WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, + WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`), taskID, id.RepositoryID, id.ProjectPath, id.MRIID) if err != nil { return err @@ -622,7 +624,7 @@ func resetMRTerminalCheckpointsOnReenable( // exhaustion error is cleared along with it; any other kind of error (sync, // merge) is left untouched. func resetMRAutoFixState(ctx context.Context, exec execContext, taskID string, id MRIdentity, now time.Time) error { - _, err := exec.ExecContext(ctx, ` + _, err := exec.ExecContext(ctx, exec.Rebind(` UPDATE gitlab_task_mr_state SET auto_fix_round_count = 0, last_fix_signature = '', @@ -632,7 +634,7 @@ func resetMRAutoFixState(ctx context.Context, exec execContext, taskID string, i last_error = CASE WHEN auto_fix_exhausted_at IS NOT NULL THEN NULL ELSE last_error END, auto_fix_exhausted_at = NULL, updated_at = ? - WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, + WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`), now, taskID, id.RepositoryID, id.ProjectPath, id.MRIID) return err } @@ -649,9 +651,9 @@ const mrLifecycleStateSelectCols = `task_id, repository_id, project_path, mr_iid // nil when no evaluation has run yet (silent-baseline case, AC10). func (s *Store) GetTaskMRLifecycleState(ctx context.Context, taskID, repositoryID, projectPath string, mrIID int) (*TaskMRLifecycleState, error) { var row TaskMRLifecycleState - err := s.ro.GetContext(ctx, &row, ` + err := s.ro.GetContext(ctx, &row, s.ro.Rebind(` SELECT `+mrLifecycleStateSelectCols+` FROM gitlab_task_mr_state - WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, + WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`), taskID, repositoryID, projectPath, mrIID) if errors.Is(err, sql.ErrNoRows) { return nil, nil @@ -665,9 +667,9 @@ func (s *Store) GetTaskMRLifecycleState(ctx context.Context, taskID, repositoryI // ListTaskMRLifecycleStates returns every checkpoint row for a task. func (s *Store) ListTaskMRLifecycleStates(ctx context.Context, taskID string) ([]*TaskMRLifecycleState, error) { var rows []TaskMRLifecycleState - if err := s.ro.SelectContext(ctx, &rows, + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( `SELECT `+mrLifecycleStateSelectCols+` FROM gitlab_task_mr_state - WHERE task_id = ? ORDER BY project_path ASC, mr_iid ASC`, taskID); err != nil { + WHERE task_id = ? ORDER BY project_path ASC, mr_iid ASC`), taskID); err != nil { return nil, err } out := make([]*TaskMRLifecycleState, 0, len(rows)) @@ -684,15 +686,15 @@ func (s *Store) ListTaskMRLifecycleStates(ctx context.Context, taskID string) ([ // write to this same row. func (s *Store) SetTaskMRReviewRequestState(ctx context.Context, taskID, repositoryID, projectPath string, mrIID int, requested bool) error { now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO gitlab_task_mr_state ( task_id, repository_id, project_path, mr_iid, review_request_initialized, last_review_requested, created_at, updated_at - ) VALUES (?, ?, ?, ?, 1, ?, ?, ?) + ) VALUES (?, ?, ?, ?, TRUE, ?, ?, ?) ON CONFLICT(task_id, repository_id, project_path, mr_iid) DO UPDATE SET - review_request_initialized = 1, + review_request_initialized = TRUE, last_review_requested = excluded.last_review_requested, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), taskID, repositoryID, projectPath, mrIID, requested, now, now) return err } @@ -703,7 +705,7 @@ func (s *Store) SetTaskMRReviewRequestState(ctx context.Context, taskID, reposit // fire its prompt again (matches GitHub's SetTaskPRObservedState). func (s *Store) SetTaskMRObservedState(ctx context.Context, taskID, repositoryID, projectPath string, mrIID int, state string) error { now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO gitlab_task_mr_state ( task_id, repository_id, project_path, mr_iid, last_observed_state, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?) @@ -713,7 +715,7 @@ func (s *Store) SetTaskMRObservedState(ctx context.Context, taskID, repositoryID WHEN excluded.last_observed_state IN (?, ?) THEN gitlab_task_mr_state.last_lifecycle_event ELSE '' END, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), taskID, repositoryID, projectPath, mrIID, state, now, now, gitlabStateMerged, gitlabStateClosed) return err } @@ -733,15 +735,15 @@ func (s *Store) RecordTaskMRLifecyclePrompt(ctx context.Context, prompt TaskMRLi sessionID = &prompt.SessionID } isReviewRequested := prompt.Event == mrLifecycleEventReviewRequested - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO gitlab_task_mr_state ( task_id, repository_id, project_path, mr_iid, review_request_initialized, last_review_requested, last_observed_state, last_lifecycle_event, last_lifecycle_prompt_at, last_lifecycle_session_id, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(task_id, repository_id, project_path, mr_iid) DO UPDATE SET - review_request_initialized = CASE - WHEN excluded.last_lifecycle_event = ? THEN 1 + review_request_initialized = CASE + WHEN excluded.last_lifecycle_event = ? THEN TRUE ELSE gitlab_task_mr_state.review_request_initialized END, last_review_requested = CASE WHEN excluded.last_lifecycle_event = ? THEN excluded.last_review_requested @@ -752,8 +754,8 @@ func (s *Store) RecordTaskMRLifecyclePrompt(ctx context.Context, prompt TaskMRLi last_lifecycle_event = excluded.last_lifecycle_event, last_lifecycle_prompt_at = excluded.last_lifecycle_prompt_at, last_lifecycle_session_id = excluded.last_lifecycle_session_id, - last_error = NULL, - updated_at = excluded.updated_at`, + last_error = NULL, + updated_at = excluded.updated_at`), prompt.TaskID, prompt.RepositoryID, prompt.ProjectPath, prompt.MRIID, isReviewRequested, prompt.ReviewRequested, prompt.ObservedState, prompt.Event, promptedAt, sessionID, now, now, mrLifecycleEventReviewRequested, mrLifecycleEventReviewRequested) @@ -767,13 +769,13 @@ func (s *Store) RecordTaskMRLifecyclePrompt(ctx context.Context, prompt TaskMRLi // from the poller's sync-error column. func (s *Store) RecordTaskMRAutomationError(ctx context.Context, taskID, repositoryID, projectPath string, mrIID int, message string) error { now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO gitlab_task_mr_state ( task_id, repository_id, project_path, mr_iid, last_error, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(task_id, repository_id, project_path, mr_iid) DO UPDATE SET last_error = excluded.last_error, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), taskID, repositoryID, projectPath, mrIID, message, now, now) return err } @@ -785,9 +787,9 @@ func (s *Store) RecordTaskMRAutomationError(ctx context.Context, taskID, reposit // must not clear this column (that call goes through // ClearTaskMRSyncError instead). func (s *Store) ClearTaskMRAutomationError(ctx context.Context, taskID, repositoryID, projectPath string, mrIID int) error { - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE gitlab_task_mr_state SET last_error = NULL, updated_at = ? - WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, + WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`), time.Now().UTC(), taskID, repositoryID, projectPath, mrIID) return err } @@ -798,13 +800,13 @@ func (s *Store) ClearTaskMRAutomationError(ctx context.Context, taskID, reposito // error in last_error. func (s *Store) RecordTaskMRSyncError(ctx context.Context, taskID, repositoryID, projectPath string, mrIID int, message string) error { now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO gitlab_task_mr_state ( task_id, repository_id, project_path, mr_iid, last_sync_error, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(task_id, repository_id, project_path, mr_iid) DO UPDATE SET last_sync_error = excluded.last_sync_error, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), taskID, repositoryID, projectPath, mrIID, message, now, now) return err } @@ -813,9 +815,9 @@ func (s *Store) RecordTaskMRSyncError(ctx context.Context, taskID, repositoryID, // succeeds. A blind conditional UPDATE — idempotent, does not require the // row to already exist, and only touches last_sync_error. func (s *Store) ClearTaskMRSyncError(ctx context.Context, taskID, repositoryID, projectPath string, mrIID int) error { - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE gitlab_task_mr_state SET last_sync_error = NULL, updated_at = ? - WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, + WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`), time.Now().UTC(), taskID, repositoryID, projectPath, mrIID) return err } @@ -834,7 +836,7 @@ func (s *Store) RebindTaskMRReviewer(ctx context.Context, taskID, username strin defer func() { _ = tx.Rollback() }() var current string - err = tx.GetContext(ctx, ¤t, `SELECT review_reviewer_username FROM gitlab_task_mr_options WHERE task_id = ?`, taskID) + err = tx.GetContext(ctx, ¤t, tx.Rebind(`SELECT review_reviewer_username FROM gitlab_task_mr_options WHERE task_id = ?`), taskID) if errors.Is(err, sql.ErrNoRows) { return false, nil } @@ -845,8 +847,8 @@ func (s *Store) RebindTaskMRReviewer(ctx context.Context, taskID, username strin return false, tx.Commit() } now := time.Now().UTC() - if _, err := tx.ExecContext(ctx, - `UPDATE gitlab_task_mr_options SET review_reviewer_username = ?, updated_at = ? WHERE task_id = ?`, + if _, err := tx.ExecContext(ctx, tx.Rebind( + `UPDATE gitlab_task_mr_options SET review_reviewer_username = ?, updated_at = ? WHERE task_id = ?`), username, now, taskID); err != nil { return false, err } @@ -864,19 +866,19 @@ func (s *Store) RebindTaskMRReviewer(ctx context.Context, taskID, username strin // invalidates all of them at once; a single MR's switch flip goes through // resetReviewBaselineForMR instead. func resetReviewBaselinesForTask(ctx context.Context, exec execContext, taskID string) error { - _, err := exec.ExecContext(ctx, ` + _, err := exec.ExecContext(ctx, exec.Rebind(` UPDATE gitlab_task_mr_state - SET review_request_initialized = 0, last_review_requested = 0, updated_at = ? - WHERE task_id = ?`, time.Now().UTC(), taskID) + SET review_request_initialized = FALSE, last_review_requested = FALSE, updated_at = ? + WHERE task_id = ?`), time.Now().UTC(), taskID) return err } // resetReviewBaselineForMR clears one linked MR's review-request baseline. func resetReviewBaselineForMR(ctx context.Context, exec execContext, taskID string, id MRIdentity) error { - _, err := exec.ExecContext(ctx, ` + _, err := exec.ExecContext(ctx, exec.Rebind(` UPDATE gitlab_task_mr_state - SET review_request_initialized = 0, last_review_requested = 0, updated_at = ? - WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, + SET review_request_initialized = FALSE, last_review_requested = FALSE, updated_at = ? + WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`), time.Now().UTC(), taskID, id.RepositoryID, id.ProjectPath, id.MRIID) return err } @@ -889,7 +891,7 @@ func resetReviewBaselineForMR(ctx context.Context, exec execContext, taskID stri func resetMRTerminalCheckpoint( ctx context.Context, exec execContext, taskID string, id MRIdentity, state string, now time.Time, ) error { - _, err := exec.ExecContext(ctx, ` + _, err := exec.ExecContext(ctx, exec.Rebind(` UPDATE gitlab_task_mr_state SET last_observed_state = '', last_lifecycle_event = '', @@ -897,7 +899,7 @@ func resetMRTerminalCheckpoint( last_lifecycle_session_id = NULL, updated_at = ? WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ? - AND (last_observed_state = ? OR last_lifecycle_event = ?)`, + AND (last_observed_state = ? OR last_lifecycle_event = ?)`), now, taskID, id.RepositoryID, id.ProjectPath, id.MRIID, state, state) return err } @@ -911,16 +913,16 @@ func resetMRTerminalCheckpoint( // polled just because a sibling MR has a switch on. func (s *Store) ListAutomationSubscribedTaskMRs(ctx context.Context) ([]*TaskMR, error) { var mrs []TaskMR - if err := s.ro.SelectContext(ctx, &mrs, ` + if err := s.ro.SelectContext(ctx, &mrs, s.ro.Rebind(` SELECT `+taskMRSelectColsQualified+` FROM gitlab_task_mrs gtm INNER JOIN gitlab_task_mr_automation_options o ON o.task_id = gtm.task_id AND o.repository_id = gtm.repository_id AND o.project_path = gtm.project_path AND o.mr_iid = gtm.mr_iid - WHERE o.prompt_on_review_requested = 1 OR o.prompt_on_merged = 1 OR o.prompt_on_closed = 1 - OR o.auto_fix_enabled = 1 OR o.auto_merge_enabled = 1 - ORDER BY gtm.created_at ASC`); err != nil { + WHERE o.prompt_on_review_requested = TRUE OR o.prompt_on_merged = TRUE OR o.prompt_on_closed = TRUE + OR o.auto_fix_enabled = TRUE OR o.auto_merge_enabled = TRUE + ORDER BY gtm.created_at ASC`)); err != nil { return nil, err } out := make([]*TaskMR, 0, len(mrs)) @@ -945,7 +947,7 @@ func (s *Store) RecordTaskMRFixAttempt(ctx context.Context, attempt TaskMRFixAtt if attempt.IncrementRound { roundCount = 1 } - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO gitlab_task_mr_state ( task_id, repository_id, project_path, mr_iid, last_fix_signature, last_fix_checkpoint_json, last_fix_enqueued_at, last_fix_session_id, auto_fix_round_count, auto_fix_exhausted_at, @@ -958,7 +960,7 @@ func (s *Store) RecordTaskMRFixAttempt(ctx context.Context, attempt TaskMRFixAtt last_fix_session_id = excluded.last_fix_session_id, auto_fix_round_count = gitlab_task_mr_state.auto_fix_round_count + excluded.auto_fix_round_count, last_error = NULL, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), attempt.TaskID, attempt.RepositoryID, attempt.ProjectPath, attempt.MRIID, attempt.Signature, attempt.CheckpointJSON, when, nullableString(attempt.SessionID), roundCount, now, now) return err @@ -972,7 +974,7 @@ func (s *Store) RecordTaskMRFixAttempt(ctx context.Context, attempt TaskMRFixAtt func (s *Store) RefreshTaskMRFixCheckpoint(ctx context.Context, taskID, repositoryID, projectPath string, mrIID int, signature, checkpointJSON string) error { ctx = context.WithoutCancel(ctx) now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO gitlab_task_mr_state ( task_id, repository_id, project_path, mr_iid, last_fix_signature, last_fix_checkpoint_json, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) @@ -982,7 +984,7 @@ func (s *Store) RefreshTaskMRFixCheckpoint(ctx context.Context, taskID, reposito last_fix_enqueued_at = NULL, last_fix_session_id = NULL, last_error = NULL, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), taskID, repositoryID, projectPath, mrIID, signature, checkpointJSON, now, now) return err } @@ -992,14 +994,14 @@ func (s *Store) RefreshTaskMRFixCheckpoint(ctx context.Context, taskID, reposito func (s *Store) MarkTaskMRAutoFixExhausted(ctx context.Context, taskID, repositoryID, projectPath string, mrIID int, message string) error { ctx = context.WithoutCancel(ctx) now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO gitlab_task_mr_state ( task_id, repository_id, project_path, mr_iid, auto_fix_exhausted_at, last_error, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(task_id, repository_id, project_path, mr_iid) DO UPDATE SET auto_fix_exhausted_at = excluded.auto_fix_exhausted_at, last_error = excluded.last_error, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), taskID, repositoryID, projectPath, mrIID, now, strings.TrimSpace(message), now, now) return err } @@ -1014,7 +1016,7 @@ func (s *Store) RecordTaskMRMergeAttempt(ctx context.Context, attempt TaskMRMerg when = time.Now().UTC() } now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO gitlab_task_mr_state ( task_id, repository_id, project_path, mr_iid, last_merge_signature, last_merge_attempt_at, created_at, updated_at ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) @@ -1022,7 +1024,7 @@ func (s *Store) RecordTaskMRMergeAttempt(ctx context.Context, attempt TaskMRMerg last_merge_signature = excluded.last_merge_signature, last_merge_attempt_at = excluded.last_merge_attempt_at, last_error = NULL, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), attempt.TaskID, attempt.RepositoryID, attempt.ProjectPath, attempt.MRIID, attempt.Signature, when, now, now) return err } @@ -1043,19 +1045,19 @@ func nullableString(value string) *string { // deletion; E2E reset deletes tasks directly via SQL without going through // that path in every deployment configuration, so this stays explicit. func (s *Store) deleteMRAutomationForWorkspace(ctx context.Context, tx execContext, workspaceID string) error { - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` DELETE FROM gitlab_task_mr_state WHERE task_id IN - (SELECT id FROM tasks WHERE workspace_id = ?)`, workspaceID); err != nil { + (SELECT id FROM tasks WHERE workspace_id = ?)`), workspaceID); err != nil { return fmt.Errorf("delete gitlab_task_mr_state: %w", err) } - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` DELETE FROM gitlab_task_mr_automation_options WHERE task_id IN - (SELECT id FROM tasks WHERE workspace_id = ?)`, workspaceID); err != nil { + (SELECT id FROM tasks WHERE workspace_id = ?)`), workspaceID); err != nil { return fmt.Errorf("delete gitlab_task_mr_automation_options: %w", err) } - if _, err := tx.ExecContext(ctx, ` + if _, err := tx.ExecContext(ctx, tx.Rebind(` DELETE FROM gitlab_task_mr_options WHERE task_id IN - (SELECT id FROM tasks WHERE workspace_id = ?)`, workspaceID); err != nil { + (SELECT id FROM tasks WHERE workspace_id = ?)`), workspaceID); err != nil { return fmt.Errorf("delete gitlab_task_mr_options: %w", err) } return nil diff --git a/apps/backend/internal/gitlab/store_mr_watch_migration_test.go b/apps/backend/internal/gitlab/store_mr_watch_migration_test.go index d6247f76a4..68ff79c7c2 100644 --- a/apps/backend/internal/gitlab/store_mr_watch_migration_test.go +++ b/apps/backend/internal/gitlab/store_mr_watch_migration_test.go @@ -9,6 +9,7 @@ import ( "github.com/jmoiron/sqlx" "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/testutil" ) // newLegacyMRWatchStore opens a fresh SQLite DB, creates gitlab_mr_watches @@ -93,6 +94,68 @@ func TestMigrateMRWatchUniqueKey_Legacy(t *testing.T) { } } +func TestMigrateMRWatchUniqueKey_PostgresLegacy(t *testing.T) { + database := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t)) + if _, err := database.Exec(` + CREATE TABLE workspaces (id TEXT PRIMARY KEY); + CREATE TABLE tasks ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL DEFAULT '', + archived_at TIMESTAMPTZ + ); + INSERT INTO tasks (id) VALUES ('task-1'); + CREATE TABLE gitlab_mr_watches ( + id TEXT PRIMARY KEY, + session_id TEXT NOT NULL, + task_id TEXT NOT NULL, + repository_id TEXT NOT NULL DEFAULT '', + project_path TEXT NOT NULL, + mr_iid INTEGER NOT NULL, + branch TEXT NOT NULL, + last_checked_at TIMESTAMPTZ, + last_note_at TIMESTAMPTZ, + last_pipeline_state TEXT DEFAULT '', + last_approval_state TEXT DEFAULT '', + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + UNIQUE(session_id, repository_id) + )`); err != nil { + t.Fatalf("create legacy PostgreSQL schema: %v", err) + } + now := time.Now().UTC() + if _, err := database.Exec(` + INSERT INTO gitlab_mr_watches ( + id, session_id, task_id, repository_id, project_path, mr_iid, branch, created_at, updated_at + ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`, + "watch-1", "sess-1", "task-1", "repo-1", "group/proj", 5, "feat/a", now, now); err != nil { + t.Fatalf("seed legacy PostgreSQL row: %v", err) + } + + store, err := NewStore(database, database) + if err != nil { + t.Fatalf("new store on legacy PostgreSQL schema: %v", err) + } + svc := NewService("", nil, "none", nil, newTestLogger(t)) + svc.SetStore(store) + second, err := svc.EnsureMRWatch( + context.Background(), "sess-1", "task-1", "repo-1", "group/proj", 6, "feat/b", + ) + if err != nil { + t.Fatalf("ensure second PostgreSQL branch watch: %v", err) + } + if second == nil || second.Branch != "feat/b" || second.MRIID != 6 { + t.Fatalf("unexpected second PostgreSQL branch watch: %+v", second) + } + + watches, err := store.ListMRWatchesBySession(context.Background(), "sess-1") + if err != nil { + t.Fatalf("list migrated PostgreSQL watches: %v", err) + } + if len(watches) != 2 { + t.Fatalf("expected two PostgreSQL watches after migration, got %d", len(watches)) + } +} + func TestMigrateMRWatchUniqueKey_ReplayIsNoOp(t *testing.T) { tmp := t.TempDir() dbPath := filepath.Join(tmp, "gitlab-replay.db") diff --git a/apps/backend/internal/gitlab/store_postgres_test.go b/apps/backend/internal/gitlab/store_postgres_test.go new file mode 100644 index 0000000000..afd195b14d --- /dev/null +++ b/apps/backend/internal/gitlab/store_postgres_test.go @@ -0,0 +1,187 @@ +package gitlab + +import ( + "context" + "testing" + "time" + + "github.com/kandev/kandev/internal/testutil" +) + +func TestPostgresStoreSchemaReplay(t *testing.T) { + ctx := context.Background() + database := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t)) + if _, err := database.Exec(` + CREATE TABLE workspaces (id TEXT PRIMARY KEY); + CREATE TABLE tasks ( + id TEXT PRIMARY KEY, + workspace_id TEXT NOT NULL, + archived_at TIMESTAMPTZ + ); + INSERT INTO workspaces (id) VALUES ('ws-1'); + INSERT INTO tasks (id, workspace_id, archived_at) VALUES ('task-1', 'ws-1', NULL)`); err != nil { + t.Fatalf("create prerequisite tables: %v", err) + } + + store, err := NewStore(database, database) + if err != nil { + t.Fatalf("first GitLab store schema init: %v", err) + } + if _, err := NewStore(database, database); err != nil { + t.Fatalf("second GitLab store schema init: %v", err) + } + + config := &GitLabConfig{ + Host: "https://gitlab.example.com", + AuthMethod: "pat", + Username: "alice", + } + if err := store.UpsertConfigForWorkspace(ctx, "ws-1", config); err != nil { + t.Fatalf("upsert GitLab config: %v", err) + } + gotConfig, err := store.GetConfigForWorkspace(ctx, "ws-1") + if err != nil || gotConfig == nil || gotConfig.Host != config.Host { + t.Fatalf("get GitLab config: config=%+v err=%v", gotConfig, err) + } + if updated, err := store.UpdateConfigHealthForRevision( + ctx, "ws-1", "alice", true, "", time.Now().UTC(), gotConfig.Revision, + ); err != nil || !updated { + t.Fatalf("update GitLab config health: updated=%v err=%v", updated, err) + } + + if err := store.UpsertMentionScope(ctx, &MentionScope{ + WorkspaceID: "ws-1", + Host: "https://gitlab.example.com", + Projects: []MentionProjectScope{{ID: 7, Path: "group/project"}}, + }); err != nil { + t.Fatalf("upsert GitLab mention scope: %v", err) + } + gotScope, err := store.GetMentionScope(ctx, "ws-1") + if err != nil || gotScope == nil || len(gotScope.Projects) != 1 { + t.Fatalf("get GitLab mention scope: scope=%+v err=%v", gotScope, err) + } + + mergeRequest := &TaskMR{ + TaskID: "task-1", + ProjectPath: "group/project", + MRIID: 42, + MRURL: "https://gitlab.example.com/group/project/-/merge_requests/42", + MRTitle: "Parity", + HeadBranch: "feature/parity", + BaseBranch: "main", + Draft: true, + } + if err := store.UpsertTaskMR(ctx, mergeRequest); err != nil { + t.Fatalf("upsert GitLab task MR: %v", err) + } + gotMR, err := store.GetTaskMR(ctx, "task-1", "", "group/project", 42) + if err != nil || gotMR == nil || !gotMR.Draft { + t.Fatalf("get GitLab task MR: mr=%+v err=%v", gotMR, err) + } + if err := store.UpdateTaskMRUnresolvedDiscussions(ctx, mergeRequest.ID, 3); err != nil { + t.Fatalf("update GitLab task MR discussions: %v", err) + } + + identity := MRIdentity{ProjectPath: "group/project", MRIID: 42} + trueValue := true + options, err := store.UpdateTaskMRAutomationOptionsForMR(ctx, "task-1", identity, TaskMRAutomationSwitchPatch{ + AutoMergeEnabled: &trueValue, + PromptOnReviewRequested: &trueValue, + }) + if err != nil || options == nil || !options.AutoMergeEnabled || !options.PromptOnReviewRequested { + t.Fatalf("update GitLab MR automation: options=%+v err=%v", options, err) + } + if err := store.SetTaskMRReviewRequestState(ctx, "task-1", "", "group/project", 42, true); err != nil { + t.Fatalf("set GitLab MR review state: %v", err) + } + if err := store.SetTaskMRObservedState(ctx, "task-1", "", "group/project", 42, gitlabStateMerged); err != nil { + t.Fatalf("set GitLab MR observed state: %v", err) + } + if err := store.RecordTaskMRLifecyclePrompt(ctx, TaskMRLifecyclePrompt{ + TaskID: "task-1", + ProjectPath: "group/project", + MRIID: 42, + Event: mrLifecycleEventReviewRequested, + ReviewRequested: true, + }); err != nil { + t.Fatalf("record GitLab MR lifecycle prompt: %v", err) + } + if _, err := store.GetTaskMRLifecycleState(ctx, "task-1", "", "group/project", 42); err != nil { + t.Fatalf("get GitLab MR lifecycle state: %v", err) + } + if subscribed, err := store.ListAutomationSubscribedTaskMRs(ctx); err != nil || len(subscribed) != 1 { + t.Fatalf("list GitLab automation MRs: mrs=%d err=%v", len(subscribed), err) + } + + refreshWatch := &MRWatch{ + SessionID: "session-1", + TaskID: "task-1", + ProjectPath: "group/project", + MRIID: 42, + Branch: "feature/parity", + } + if err := store.CreateMRWatch(ctx, refreshWatch); err != nil { + t.Fatalf("create GitLab MR watch: %v", err) + } + if got, err := store.GetMRWatchBySession(ctx, "session-1"); err != nil || got == nil { + t.Fatalf("get GitLab MR watch: watch=%+v err=%v", got, err) + } + + reviewWatch := &ReviewWatch{ + WorkspaceID: "ws-1", + WorkflowID: "workflow-1", + WorkflowStepID: "step-1", + Projects: []ProjectFilter{{Path: "group/project"}}, + AgentProfileID: "agent-1", + ExecutorProfileID: "executor-1", + Enabled: true, + } + if err := store.CreateReviewWatch(ctx, reviewWatch); err != nil { + t.Fatalf("create GitLab review watch: %v", err) + } + if _, err := store.ListEnabledReviewWatchesForWorkspace(ctx, "ws-1"); err != nil { + t.Fatalf("list GitLab review watches: %v", err) + } + reserved, err := store.ReserveReviewMRTask(ctx, reviewWatch.ID, "group/project", 43, "https://gitlab.example.com/mr/43") + if err != nil || !reserved { + t.Fatalf("reserve GitLab review MR task: reserved=%v err=%v", reserved, err) + } + if err := store.AssignReviewMRTaskID(ctx, reviewWatch.ID, "group/project", 43, "task-1"); err != nil { + t.Fatalf("assign GitLab review MR task: %v", err) + } + + issueWatch := &IssueWatch{ + WorkspaceID: "ws-1", + WorkflowID: "workflow-1", + WorkflowStepID: "step-1", + Projects: []ProjectFilter{{Path: "group/project"}}, + Labels: []string{"bug"}, + AgentProfileID: "agent-1", + ExecutorProfileID: "executor-1", + Enabled: true, + } + if err := store.CreateIssueWatch(ctx, issueWatch); err != nil { + t.Fatalf("create GitLab issue watch: %v", err) + } + if _, err := store.ListEnabledIssueWatchesForWorkspace(ctx, "ws-1"); err != nil { + t.Fatalf("list GitLab issue watches: %v", err) + } + reserved, err = store.ReserveIssueWatchTask(ctx, issueWatch.ID, "group/project", 9, "https://gitlab.example.com/issue/9") + if err != nil || !reserved { + t.Fatalf("reserve GitLab issue task: reserved=%v err=%v", reserved, err) + } + if err := store.AssignIssueWatchTaskID(ctx, issueWatch.ID, "group/project", 9, "task-1"); err != nil { + t.Fatalf("assign GitLab issue task: %v", err) + } + + if err := store.UpsertActionPresets(ctx, &ActionPresets{ + WorkspaceID: "ws-1", + MR: DefaultMRActionPresets(), + Issue: DefaultIssueActionPresets(), + }); err != nil { + t.Fatalf("upsert GitLab action presets: %v", err) + } + if _, err := store.GetActionPresets(ctx, "ws-1"); err != nil { + t.Fatalf("get GitLab action presets: %v", err) + } +} diff --git a/apps/backend/internal/gitlab/store_task_cleanup.go b/apps/backend/internal/gitlab/store_task_cleanup.go index a01df0e5ff..0522432fee 100644 --- a/apps/backend/internal/gitlab/store_task_cleanup.go +++ b/apps/backend/internal/gitlab/store_task_cleanup.go @@ -2,9 +2,9 @@ package gitlab import ( "context" - "database/sql" - "errors" "fmt" + + dbutil "github.com/kandev/kandev/internal/db" ) var gitlabTaskOwnedTables = []string{ @@ -17,7 +17,7 @@ var gitlabTaskOwnedTables = []string{ // DeleteTaskMRsByTaskID removes every contribution association owned by a // hard-deleted task. It is safe to replay after a missed event. func (s *Store) DeleteTaskMRsByTaskID(ctx context.Context, taskID string) (int64, error) { - result, err := s.db.ExecContext(ctx, `DELETE FROM gitlab_task_mrs WHERE task_id = ?`, taskID) + result, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM gitlab_task_mrs WHERE task_id = ?`), taskID) if err != nil { return 0, err } @@ -35,7 +35,7 @@ func (s *Store) DeleteTaskOwnedStateByTaskID(ctx context.Context, taskID string) var deleted int64 for _, table := range gitlabTaskOwnedTables { - result, err := tx.ExecContext(ctx, `DELETE FROM `+table+` WHERE task_id = ?`, taskID) + result, err := tx.ExecContext(ctx, tx.Rebind(`DELETE FROM `+table+` WHERE task_id = ?`), taskID) if err != nil { return 0, fmt.Errorf("delete task-owned rows from %s: %w", table, err) } @@ -52,14 +52,13 @@ func (s *Store) DeleteTaskOwnedStateByTaskID(ctx context.Context, taskID string) } func (s *Store) healTaskOwnedOrphans() error { - var exists int - err := s.db.Get(&exists, `SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'tasks'`) - if errors.Is(err, sql.ErrNoRows) { - return nil // tasks table not yet created — skip sweep - } + exists, err := dbutil.TableExists(s.db, "tasks") if err != nil { return err } + if !exists { + return nil // tasks table not yet created — skip sweep + } tx, err := s.db.Beginx() if err != nil { return fmt.Errorf("begin orphan sweep: %w", err) diff --git a/apps/backend/internal/gitlab/store_task_mr_link.go b/apps/backend/internal/gitlab/store_task_mr_link.go index 18668182ae..ac566a3d03 100644 --- a/apps/backend/internal/gitlab/store_task_mr_link.go +++ b/apps/backend/internal/gitlab/store_task_mr_link.go @@ -17,8 +17,8 @@ import ( // share one error so callers do not disclose resource existence. func (s *Store) ValidateTaskMRScope(ctx context.Context, workspaceID, taskID, repositoryID string) error { var taskExists int - err := s.ro.GetContext(ctx, &taskExists, - `SELECT 1 FROM tasks WHERE id = ? AND workspace_id = ? LIMIT 1`, taskID, workspaceID) + err := s.ro.GetContext(ctx, &taskExists, s.ro.Rebind( + `SELECT 1 FROM tasks WHERE id = ? AND workspace_id = ? LIMIT 1`), taskID, workspaceID) if errors.Is(err, sql.ErrNoRows) { return ErrTaskMRNotFound } @@ -29,12 +29,12 @@ func (s *Store) ValidateTaskMRScope(ctx context.Context, workspaceID, taskID, re return nil } var repositoryExists int - err = s.ro.GetContext(ctx, &repositoryExists, ` + err = s.ro.GetContext(ctx, &repositoryExists, s.ro.Rebind(` SELECT 1 FROM task_repositories tr JOIN repositories r ON r.id = tr.repository_id WHERE tr.task_id = ? AND tr.repository_id = ? AND r.workspace_id = ? - LIMIT 1`, taskID, repositoryID, workspaceID) + LIMIT 1`), taskID, repositoryID, workspaceID) if errors.Is(err, sql.ErrNoRows) { return ErrTaskMRNotFound } @@ -70,7 +70,7 @@ func (s *Store) ValidateTaskMRRepositoryIdentity( return ErrTaskMRRepositoryMismatch } var identity taskMRRepositoryIdentityRow - err := s.ro.GetContext(ctx, &identity, ` + err := s.ro.GetContext(ctx, &identity, s.ro.Rebind(` SELECT COALESCE(r.provider, '') AS provider, COALESCE(r.provider_repo_id, '') AS provider_repo_id, COALESCE(r.provider_host, '') AS provider_host, @@ -83,7 +83,7 @@ func (s *Store) ValidateTaskMRRepositoryIdentity( JOIN tasks t ON t.id = tr.task_id WHERE tr.task_id = ? AND tr.repository_id = ? AND t.workspace_id = ? AND r.workspace_id = ? - LIMIT 1`, taskID, repositoryID, workspaceID, workspaceID) + LIMIT 1`), taskID, repositoryID, workspaceID, workspaceID) if errors.Is(err, sql.ErrNoRows) { return ErrTaskMRNotFound } @@ -189,10 +189,10 @@ func localCheckoutIdentityCandidate(localPath string) (candidate taskMRIdentityC // effort: failures are swallowed since the caller already has what it needs // to proceed with the current request. func (s *Store) backfillRepositoryRemoteURL(ctx context.Context, repositoryID, remoteURL string) { - _, _ = s.db.ExecContext(ctx, ` + _, _ = s.db.ExecContext(ctx, s.db.Rebind(` UPDATE repositories SET remote_url = ?, updated_at = ? - WHERE id = ? AND (remote_url IS NULL OR remote_url = '')`, + WHERE id = ? AND (remote_url IS NULL OR remote_url = '')`), remoteURL, time.Now().UTC(), repositoryID) } @@ -347,12 +347,12 @@ func (s *Store) ResolveTaskMRRepository( return "", err } var repositoryIDs []string - if err := s.ro.SelectContext(ctx, &repositoryIDs, ` + if err := s.ro.SelectContext(ctx, &repositoryIDs, s.ro.Rebind(` SELECT tr.repository_id FROM task_repositories tr JOIN repositories r ON r.id = tr.repository_id WHERE tr.task_id = ? AND r.workspace_id = ? - ORDER BY tr.id`, taskID, workspaceID); err != nil { + ORDER BY tr.id`), taskID, workspaceID); err != nil { return "", fmt.Errorf("list task repositories: %w", err) } switch len(repositoryIDs) { @@ -375,28 +375,28 @@ func (s *Store) DeleteTaskMRForWorkspace(ctx context.Context, workspaceID, assoc defer func() { _ = tx.Rollback() }() var association TaskMR - err = tx.GetContext(ctx, &association, ` + err = tx.GetContext(ctx, &association, tx.Rebind(` SELECT `+taskMRSelectColsQualified+` FROM gitlab_task_mrs gtm JOIN tasks t ON t.id = gtm.task_id WHERE gtm.id = ? AND t.workspace_id = ? - LIMIT 1`, associationID, workspaceID) + LIMIT 1`), associationID, workspaceID) if errors.Is(err, sql.ErrNoRows) { return ErrTaskMRNotFound } if err != nil { return fmt.Errorf("find task MR association: %w", err) } - if _, err = tx.ExecContext(ctx, ` + if _, err = tx.ExecContext(ctx, tx.Rebind(` DELETE FROM gitlab_mr_watches - WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, + WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`), association.TaskID, association.RepositoryID, association.ProjectPath, association.MRIID, ); err != nil { return fmt.Errorf("delete task MR refresh watch: %w", err) } - if _, err = tx.ExecContext(ctx, ` + if _, err = tx.ExecContext(ctx, tx.Rebind(` DELETE FROM gitlab_task_mr_state - WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, + WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`), association.TaskID, association.RepositoryID, association.ProjectPath, association.MRIID, ); err != nil { return fmt.Errorf("delete task MR lifecycle state: %w", err) @@ -408,14 +408,14 @@ func (s *Store) DeleteTaskMRForWorkspace(ctx context.Context, workspaceID, assoc // "stop automating this" action, so it must not leave a latent enabled // switch that no surface displays (taskMRAutomationOptionsList hides rows // whose MR is not linked) but the evaluator still reads. - if _, err = tx.ExecContext(ctx, ` + if _, err = tx.ExecContext(ctx, tx.Rebind(` DELETE FROM gitlab_task_mr_automation_options - WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`, + WHERE task_id = ? AND repository_id = ? AND project_path = ? AND mr_iid = ?`), association.TaskID, association.RepositoryID, association.ProjectPath, association.MRIID, ); err != nil { return fmt.Errorf("delete task MR automation options: %w", err) } - if _, err = tx.ExecContext(ctx, `DELETE FROM gitlab_task_mrs WHERE id = ?`, association.ID); err != nil { + if _, err = tx.ExecContext(ctx, tx.Rebind(`DELETE FROM gitlab_task_mrs WHERE id = ?`), association.ID); err != nil { return fmt.Errorf("delete task MR association: %w", err) } return tx.Commit() diff --git a/apps/backend/internal/gitlab/store_watch_reset.go b/apps/backend/internal/gitlab/store_watch_reset.go index ab3c8ff2f8..da00ee9fd4 100644 --- a/apps/backend/internal/gitlab/store_watch_reset.go +++ b/apps/backend/internal/gitlab/store_watch_reset.go @@ -39,10 +39,10 @@ func (s *Store) beginWatchInvalidation(ctx context.Context, watchTable, taskTabl defer func() { _ = tx.Rollback() }() set := "generation = generation + 1, updated_at = CURRENT_TIMESTAMP" if deleting { - set += ", deleting = 1, enabled = 0" + set += ", deleting = TRUE, enabled = FALSE" } - result, err := tx.ExecContext(ctx, - fmt.Sprintf("UPDATE %s SET %s WHERE id = ? AND deleting = 0", watchTable, set), watchID) + result, err := tx.ExecContext(ctx, tx.Rebind( + fmt.Sprintf("UPDATE %s SET %s WHERE id = ? AND deleting = FALSE", watchTable, set)), watchID) if err != nil { return nil, err } @@ -57,13 +57,13 @@ func (s *Store) beginWatchInvalidation(ctx context.Context, watchTable, taskTabl return s.resumeWatchDelete(ctx, tx, watchTable, taskTable, foreignKey, watchID) } var generation int64 - if err := tx.GetContext(ctx, &generation, - fmt.Sprintf("SELECT generation FROM %s WHERE id = ?", watchTable), watchID); err != nil { + if err := tx.GetContext(ctx, &generation, tx.Rebind( + fmt.Sprintf("SELECT generation FROM %s WHERE id = ?", watchTable)), watchID); err != nil { return nil, err } var taskIDs []string - if err := tx.SelectContext(ctx, &taskIDs, - fmt.Sprintf("SELECT task_id FROM %s WHERE %s = ? AND generation < ? AND task_id <> '' ORDER BY created_at", taskTable, foreignKey), + if err := tx.SelectContext(ctx, &taskIDs, tx.Rebind( + fmt.Sprintf("SELECT task_id FROM %s WHERE %s = ? AND generation < ? AND task_id <> '' ORDER BY created_at", taskTable, foreignKey)), watchID, generation); err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, err } @@ -78,8 +78,8 @@ func (s *Store) resumeWatchDelete(ctx context.Context, tx *sqlx.Tx, watchTable, Generation int64 `db:"generation"` Deleting bool `db:"deleting"` } - err := tx.GetContext(ctx, &state, - fmt.Sprintf("SELECT generation, deleting FROM %s WHERE id = ?", watchTable), watchID) + err := tx.GetContext(ctx, &state, tx.Rebind( + fmt.Sprintf("SELECT generation, deleting FROM %s WHERE id = ?", watchTable)), watchID) if errors.Is(err, sql.ErrNoRows) { return &watchInvalidation{Missing: true}, nil } @@ -90,8 +90,8 @@ func (s *Store) resumeWatchDelete(ctx context.Context, tx *sqlx.Tx, watchTable, return nil, ErrWatchOwnershipLost } var taskIDs []string - if err := tx.SelectContext(ctx, &taskIDs, - fmt.Sprintf("SELECT task_id FROM %s WHERE %s = ? AND generation < ? AND task_id <> '' ORDER BY created_at", taskTable, foreignKey), + if err := tx.SelectContext(ctx, &taskIDs, tx.Rebind( + fmt.Sprintf("SELECT task_id FROM %s WHERE %s = ? AND generation < ? AND task_id <> '' ORDER BY created_at", taskTable, foreignKey)), watchID, state.Generation); err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, err } @@ -115,12 +115,12 @@ func (s *Store) finishWatchReset(ctx context.Context, watchTable, taskTable, for return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, - fmt.Sprintf("DELETE FROM %s WHERE %s = ? AND generation < ?", taskTable, foreignKey), watchID, generation); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind( + fmt.Sprintf("DELETE FROM %s WHERE %s = ? AND generation < ?", taskTable, foreignKey)), watchID, generation); err != nil { return err } - result, err := tx.ExecContext(ctx, - fmt.Sprintf("UPDATE %s SET last_polled_at = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND generation = ? AND deleting = 0", watchTable), + result, err := tx.ExecContext(ctx, tx.Rebind( + fmt.Sprintf("UPDATE %s SET last_polled_at = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ? AND generation = ? AND deleting = FALSE", watchTable)), watchID, generation) if err != nil { return err @@ -137,8 +137,8 @@ func (s *Store) finishWatchReset(ctx context.Context, watchTable, taskTable, for func (s *Store) ListReviewMRTaskIDsByWatch(ctx context.Context, watchID string) ([]string, error) { var ids []string - if err := s.ro.SelectContext(ctx, &ids, - `SELECT task_id FROM gitlab_review_mr_tasks WHERE review_watch_id = ? ORDER BY created_at`, watchID); err != nil { + if err := s.ro.SelectContext(ctx, &ids, s.ro.Rebind( + `SELECT task_id FROM gitlab_review_mr_tasks WHERE review_watch_id = ? ORDER BY created_at`), watchID); err != nil { return nil, err } return ids, nil @@ -150,10 +150,10 @@ func (s *Store) ResetReviewWatchState(ctx context.Context, watchID string) error return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, `DELETE FROM gitlab_review_mr_tasks WHERE review_watch_id = ?`, watchID); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(`DELETE FROM gitlab_review_mr_tasks WHERE review_watch_id = ?`), watchID); err != nil { return fmt.Errorf("clear review watch tasks: %w", err) } - if _, err := tx.ExecContext(ctx, `UPDATE gitlab_review_watches SET last_polled_at = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, watchID); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(`UPDATE gitlab_review_watches SET last_polled_at = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?`), watchID); err != nil { return fmt.Errorf("clear review watch poll state: %w", err) } return tx.Commit() @@ -161,8 +161,8 @@ func (s *Store) ResetReviewWatchState(ctx context.Context, watchID string) error func (s *Store) ListIssueWatchTaskIDsByWatch(ctx context.Context, watchID string) ([]string, error) { var ids []string - if err := s.ro.SelectContext(ctx, &ids, - `SELECT task_id FROM gitlab_issue_watch_tasks WHERE issue_watch_id = ? ORDER BY created_at`, watchID); err != nil { + if err := s.ro.SelectContext(ctx, &ids, s.ro.Rebind( + `SELECT task_id FROM gitlab_issue_watch_tasks WHERE issue_watch_id = ? ORDER BY created_at`), watchID); err != nil { return nil, err } return ids, nil @@ -174,10 +174,10 @@ func (s *Store) ResetIssueWatchState(ctx context.Context, watchID string) error return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, `DELETE FROM gitlab_issue_watch_tasks WHERE issue_watch_id = ?`, watchID); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(`DELETE FROM gitlab_issue_watch_tasks WHERE issue_watch_id = ?`), watchID); err != nil { return fmt.Errorf("clear issue watch tasks: %w", err) } - if _, err := tx.ExecContext(ctx, `UPDATE gitlab_issue_watches SET last_polled_at = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?`, watchID); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(`UPDATE gitlab_issue_watches SET last_polled_at = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?`), watchID); err != nil { return fmt.Errorf("clear issue watch poll state: %w", err) } return tx.Commit() diff --git a/apps/backend/internal/gitlab/store_watches.go b/apps/backend/internal/gitlab/store_watches.go index c57832a1a4..41258d5e06 100644 --- a/apps/backend/internal/gitlab/store_watches.go +++ b/apps/backend/internal/gitlab/store_watches.go @@ -49,9 +49,9 @@ func (s *Store) GetMRWatchBySession(ctx context.Context, sessionID string) (*MRW // GetMRWatchBySessionAndRepo returns the MR watch keyed by (session, repository). func (s *Store) GetMRWatchBySessionAndRepo(ctx context.Context, sessionID, repositoryID string) (*MRWatch, error) { var w MRWatch - err := s.ro.GetContext(ctx, &w, + err := s.ro.GetContext(ctx, &w, s.ro.Rebind( `SELECT `+mrWatchSelectCols+` FROM gitlab_mr_watches - WHERE session_id = ? AND repository_id = ? LIMIT 1`, sessionID, repositoryID) + WHERE session_id = ? AND repository_id = ? LIMIT 1`), sessionID, repositoryID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -68,9 +68,9 @@ func (s *Store) GetMRWatchBySessionAndRepo(ctx context.Context, sessionID, repos // found. func (s *Store) GetMRWatchBySessionRepoAndBranch(ctx context.Context, sessionID, repositoryID, branch string) (*MRWatch, error) { var w MRWatch - err := s.ro.GetContext(ctx, &w, + err := s.ro.GetContext(ctx, &w, s.ro.Rebind( `SELECT `+mrWatchSelectCols+` FROM gitlab_mr_watches - WHERE session_id = ? AND repository_id = ? AND branch = ? LIMIT 1`, sessionID, repositoryID, branch) + WHERE session_id = ? AND repository_id = ? AND branch = ? LIMIT 1`), sessionID, repositoryID, branch) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -83,9 +83,9 @@ func (s *Store) GetMRWatchBySessionRepoAndBranch(ctx context.Context, sessionID, // ListMRWatchesBySession returns every MR watch for a session. func (s *Store) ListMRWatchesBySession(ctx context.Context, sessionID string) ([]*MRWatch, error) { var ws []MRWatch - if err := s.ro.SelectContext(ctx, &ws, + if err := s.ro.SelectContext(ctx, &ws, s.ro.Rebind( `SELECT `+mrWatchSelectCols+` FROM gitlab_mr_watches - WHERE session_id = ? ORDER BY created_at ASC`, sessionID); err != nil { + WHERE session_id = ? ORDER BY created_at ASC`), sessionID); err != nil { return nil, err } out := make([]*MRWatch, 0, len(ws)) @@ -105,9 +105,9 @@ func (s *Store) ListMRWatchesBySessionForWorkspace(ctx context.Context, workspac // ListMRWatchesByTask returns every MR watch for a task. func (s *Store) ListMRWatchesByTask(ctx context.Context, taskID string) ([]*MRWatch, error) { var ws []MRWatch - if err := s.ro.SelectContext(ctx, &ws, + if err := s.ro.SelectContext(ctx, &ws, s.ro.Rebind( `SELECT `+mrWatchSelectCols+` FROM gitlab_mr_watches - WHERE task_id = ? ORDER BY created_at ASC`, taskID); err != nil { + WHERE task_id = ? ORDER BY created_at ASC`), taskID); err != nil { return nil, err } out := make([]*MRWatch, 0, len(ws)) @@ -124,8 +124,8 @@ func (s *Store) ListMRWatchesByTaskForWorkspace(ctx context.Context, workspaceID // ListActiveMRWatches returns every persisted MR watch (used by the poller). func (s *Store) ListActiveMRWatches(ctx context.Context) ([]*MRWatch, error) { var ws []MRWatch - if err := s.ro.SelectContext(ctx, &ws, - `SELECT `+mrWatchSelectCols+` FROM gitlab_mr_watches ORDER BY created_at ASC`); err != nil { + if err := s.ro.SelectContext(ctx, &ws, s.ro.Rebind( + `SELECT `+mrWatchSelectCols+` FROM gitlab_mr_watches ORDER BY created_at ASC`)); err != nil { return nil, err } out := make([]*MRWatch, 0, len(ws)) @@ -143,13 +143,13 @@ func (s *Store) ListActiveMRWatchesForWorkspace(ctx context.Context, workspaceID func (s *Store) listMRWatchesForWorkspace(ctx context.Context, workspaceID, predicate string, args ...interface{}) ([]*MRWatch, error) { queryArgs := append([]interface{}{workspaceID}, args...) var rows []MRWatch - if err := s.ro.SelectContext(ctx, &rows, + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( `SELECT w.id, w.session_id, w.task_id, w.repository_id, w.project_path, w.mr_iid, w.branch, w.last_checked_at, w.last_note_at, w.last_pipeline_state, w.last_approval_state, w.created_at, w.updated_at FROM gitlab_mr_watches w JOIN tasks t ON t.id = w.task_id - WHERE t.workspace_id = ? AND `+predicate+` ORDER BY w.created_at ASC`, queryArgs...); err != nil { + WHERE t.workspace_id = ? AND `+predicate+` ORDER BY w.created_at ASC`), queryArgs...); err != nil { return nil, err } out := make([]*MRWatch, 0, len(rows)) @@ -161,33 +161,33 @@ func (s *Store) listMRWatchesForWorkspace(ctx context.Context, workspaceID, pred // UpdateMRWatchTimestamps records the last poll cycle's observation. func (s *Store) UpdateMRWatchTimestamps(ctx context.Context, id string, checkedAt time.Time, noteAt *time.Time, pipelineState, approvalState string) error { - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE gitlab_mr_watches SET last_checked_at = ?, last_note_at = ?, last_pipeline_state = ?, last_approval_state = ?, updated_at = ? - WHERE id = ?`, checkedAt, noteAt, pipelineState, approvalState, time.Now().UTC(), id) + WHERE id = ?`), checkedAt, noteAt, pipelineState, approvalState, time.Now().UTC(), id) return err } // UpdateMRWatchMRIID stamps the watch with the MR iid once detected. func (s *Store) UpdateMRWatchMRIID(ctx context.Context, id string, iid int) error { - _, err := s.db.ExecContext(ctx, - `UPDATE gitlab_mr_watches SET mr_iid = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE gitlab_mr_watches SET mr_iid = ?, updated_at = ? WHERE id = ?`), iid, time.Now().UTC(), id) return err } // DeleteMRWatch removes a single MR watch by id. func (s *Store) DeleteMRWatch(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM gitlab_mr_watches WHERE id = ?`, id) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM gitlab_mr_watches WHERE id = ?`), id) return err } func (s *Store) DeleteMRWatchForWorkspace(ctx context.Context, workspaceID, id string) (bool, error) { - result, err := s.db.ExecContext(ctx, `DELETE FROM gitlab_mr_watches + result, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM gitlab_mr_watches WHERE id = ? AND EXISTS ( SELECT 1 FROM tasks t WHERE t.id = gitlab_mr_watches.task_id AND t.workspace_id = ? - )`, id, workspaceID) + )`), id, workspaceID) if err != nil { return false, err } @@ -197,8 +197,8 @@ func (s *Store) DeleteMRWatchForWorkspace(ctx context.Context, workspaceID, id s // DeleteMRWatchesByTaskID removes all MR watches associated with a task. func (s *Store) DeleteMRWatchesByTaskID(ctx context.Context, taskID string) (int64, error) { - res, err := s.db.ExecContext(ctx, - `DELETE FROM gitlab_mr_watches WHERE task_id = ?`, taskID) + res, err := s.db.ExecContext(ctx, s.db.Rebind( + `DELETE FROM gitlab_mr_watches WHERE task_id = ?`), taskID) if err != nil { return 0, err } @@ -263,12 +263,12 @@ func (s *Store) GetReviewWatchIncludingDeleting(ctx context.Context, id string) func (s *Store) getReviewWatch(ctx context.Context, id string, includeDeleting bool) (*ReviewWatch, error) { var rw ReviewWatch - deletingClause := " AND deleting = 0" + deletingClause := " AND deleting = FALSE" if includeDeleting { deletingClause = "" } - err := s.ro.GetContext(ctx, &rw, - `SELECT `+reviewWatchSelectCols+` FROM gitlab_review_watches WHERE id = ?`+deletingClause, id) + err := s.ro.GetContext(ctx, &rw, s.ro.Rebind( + `SELECT `+reviewWatchSelectCols+` FROM gitlab_review_watches WHERE id = ?`+deletingClause), id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -285,31 +285,31 @@ func (s *Store) getReviewWatch(ctx context.Context, id string, includeDeleting b func (s *Store) ListReviewWatches(ctx context.Context, workspaceID string) ([]*ReviewWatch, error) { return s.listReviewWatches(ctx, `SELECT `+reviewWatchSelectCols+` FROM gitlab_review_watches - WHERE workspace_id = ? AND deleting = 0 ORDER BY created_at ASC`, workspaceID) + WHERE workspace_id = ? AND deleting = FALSE ORDER BY created_at ASC`, workspaceID) } // ListAllReviewWatches lists every review watch (used by the poller). func (s *Store) ListAllReviewWatches(ctx context.Context) ([]*ReviewWatch, error) { return s.listReviewWatches(ctx, - `SELECT `+reviewWatchSelectCols+` FROM gitlab_review_watches WHERE deleting = 0 ORDER BY created_at ASC`) + `SELECT `+reviewWatchSelectCols+` FROM gitlab_review_watches WHERE deleting = FALSE ORDER BY created_at ASC`) } // ListEnabledReviewWatches lists every enabled review watch. func (s *Store) ListEnabledReviewWatches(ctx context.Context) ([]*ReviewWatch, error) { return s.listReviewWatches(ctx, `SELECT `+reviewWatchSelectCols+` FROM gitlab_review_watches - WHERE enabled = 1 AND deleting = 0 ORDER BY created_at ASC`) + WHERE enabled = TRUE AND deleting = FALSE ORDER BY created_at ASC`) } func (s *Store) ListEnabledReviewWatchesForWorkspace(ctx context.Context, workspaceID string) ([]*ReviewWatch, error) { return s.listReviewWatches(ctx, `SELECT `+reviewWatchSelectCols+` FROM gitlab_review_watches - WHERE enabled = 1 AND deleting = 0 AND workspace_id = ? ORDER BY created_at ASC`, workspaceID) + WHERE enabled = TRUE AND deleting = FALSE AND workspace_id = ? ORDER BY created_at ASC`, workspaceID) } func (s *Store) listReviewWatches(ctx context.Context, query string, args ...interface{}) ([]*ReviewWatch, error) { var rows []ReviewWatch - if err := s.ro.SelectContext(ctx, &rows, query, args...); err != nil { + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind(query), args...); err != nil { return nil, err } out := make([]*ReviewWatch, 0, len(rows)) @@ -355,16 +355,16 @@ func (s *Store) UpdateReviewWatch(ctx context.Context, rw *ReviewWatch) error { // RecordReviewWatchPoll stamps last_polled_at without touching other fields. func (s *Store) RecordReviewWatchPoll(ctx context.Context, id string, polledAt time.Time) error { - _, err := s.db.ExecContext(ctx, - `UPDATE gitlab_review_watches SET last_polled_at = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE gitlab_review_watches SET last_polled_at = ?, updated_at = ? WHERE id = ?`), polledAt, time.Now().UTC(), id) return err } func (s *Store) DisableReviewWatchWithError(ctx context.Context, id, cause string) error { now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, `UPDATE gitlab_review_watches - SET enabled = 0, last_error = ?, last_error_at = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind(`UPDATE gitlab_review_watches + SET enabled = FALSE, last_error = ?, last_error_at = ?, updated_at = ? WHERE id = ?`), cause, now, now, id) return err } @@ -376,10 +376,10 @@ func (s *Store) DeleteReviewWatch(ctx context.Context, id string) error { return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, `DELETE FROM gitlab_review_mr_tasks WHERE review_watch_id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(`DELETE FROM gitlab_review_mr_tasks WHERE review_watch_id = ?`), id); err != nil { return err } - if _, err := tx.ExecContext(ctx, `DELETE FROM gitlab_review_watches WHERE id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(`DELETE FROM gitlab_review_watches WHERE id = ?`), id); err != nil { return err } return tx.Commit() @@ -394,9 +394,9 @@ const reviewMRTaskSelectCols = `id, review_watch_id, project_path, mr_iid, // dedup-claimed. func (s *Store) HasReviewMRTask(ctx context.Context, reviewWatchID, projectPath string, iid int) (bool, error) { var count int - err := s.ro.GetContext(ctx, &count, + err := s.ro.GetContext(ctx, &count, s.ro.Rebind( `SELECT COUNT(*) FROM gitlab_review_mr_tasks - WHERE review_watch_id = ? AND project_path = ? AND mr_iid = ?`, + WHERE review_watch_id = ? AND project_path = ? AND mr_iid = ?`), reviewWatchID, projectPath, iid) if err != nil { return false, err @@ -432,11 +432,11 @@ func (s *Store) reserveReviewMRTask(ctx context.Context, reviewWatchID string, g INSERT INTO gitlab_review_mr_tasks (id, review_watch_id, project_path, mr_iid, mr_url, task_id, generation, created_at) SELECT ?, ?, ?, ?, ?, '', ?, ? WHERE EXISTS (SELECT 1 FROM gitlab_review_watches - WHERE id = ? AND generation = ? AND enabled = 1 AND deleting = 0) + WHERE id = ? AND generation = ? AND enabled = TRUE AND deleting = FALSE) ON CONFLICT(review_watch_id, project_path, mr_iid) DO NOTHING` args = append(args, reviewWatchID, generation) } - result, err := s.db.ExecContext(ctx, query, args...) + result, err := s.db.ExecContext(ctx, s.db.Rebind(query), args...) if err != nil { return false, err } @@ -461,15 +461,15 @@ func (s *Store) assignReviewMRTaskID(ctx context.Context, reviewWatchID string, activeClause := "" if requireActive { activeClause = ` AND EXISTS (SELECT 1 FROM gitlab_review_watches - WHERE id = ? AND generation = ? AND enabled = 1 AND deleting = 0)` + WHERE id = ? AND generation = ? AND enabled = TRUE AND deleting = FALSE)` } args := []interface{}{taskID, reviewWatchID, projectPath, iid, generation} if requireActive { args = append(args, reviewWatchID, generation) } - res, err := s.db.ExecContext(ctx, ` + res, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE gitlab_review_mr_tasks SET task_id = ? - WHERE review_watch_id = ? AND project_path = ? AND mr_iid = ? AND generation = ?`+activeClause, + WHERE review_watch_id = ? AND project_path = ? AND mr_iid = ? AND generation = ?`+activeClause), args...) if err != nil { return err @@ -487,25 +487,25 @@ func (s *Store) assignReviewMRTaskID(ctx context.Context, reviewWatchID string, // ReleaseReviewMRTask removes the (failed) reservation so future polls can // retry on the same MR. func (s *Store) ReleaseReviewMRTask(ctx context.Context, reviewWatchID, projectPath string, iid int) error { - _, err := s.db.ExecContext(ctx, + _, err := s.db.ExecContext(ctx, s.db.Rebind( `DELETE FROM gitlab_review_mr_tasks - WHERE review_watch_id = ? AND project_path = ? AND mr_iid = ?`, + WHERE review_watch_id = ? AND project_path = ? AND mr_iid = ?`), reviewWatchID, projectPath, iid) return err } func (s *Store) ReleaseReviewMRTaskForGeneration(ctx context.Context, reviewWatchID string, generation int64, projectPath string, iid int) error { - _, err := s.db.ExecContext(ctx, + _, err := s.db.ExecContext(ctx, s.db.Rebind( `DELETE FROM gitlab_review_mr_tasks - WHERE review_watch_id = ? AND project_path = ? AND mr_iid = ? AND generation = ?`, + WHERE review_watch_id = ? AND project_path = ? AND mr_iid = ? AND generation = ?`), reviewWatchID, projectPath, iid, generation) return err } func (s *Store) reviewWatchGeneration(ctx context.Context, watchID string) (int64, error) { var generation int64 - if err := s.ro.GetContext(ctx, &generation, - `SELECT generation FROM gitlab_review_watches WHERE id = ?`, watchID); err != nil { + if err := s.ro.GetContext(ctx, &generation, s.ro.Rebind( + `SELECT generation FROM gitlab_review_watches WHERE id = ?`), watchID); err != nil { if errors.Is(err, sql.ErrNoRows) { return 1, nil } @@ -517,9 +517,9 @@ func (s *Store) reviewWatchGeneration(ctx context.Context, watchID string) (int6 // ListReviewMRTasksByWatch returns dedup rows for a given watch. func (s *Store) ListReviewMRTasksByWatch(ctx context.Context, watchID string) ([]*ReviewMRTask, error) { var rows []ReviewMRTask - if err := s.ro.SelectContext(ctx, &rows, + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( `SELECT `+reviewMRTaskSelectCols+` FROM gitlab_review_mr_tasks - WHERE review_watch_id = ? ORDER BY created_at ASC`, watchID); err != nil { + WHERE review_watch_id = ? ORDER BY created_at ASC`), watchID); err != nil { return nil, err } out := make([]*ReviewMRTask, 0, len(rows)) @@ -532,8 +532,8 @@ func (s *Store) ListReviewMRTasksByWatch(ctx context.Context, watchID string) ([ // ListAllReviewMRTasks returns every dedup row (used by cleanup sweepers). func (s *Store) ListAllReviewMRTasks(ctx context.Context) ([]*ReviewMRTask, error) { var rows []ReviewMRTask - if err := s.ro.SelectContext(ctx, &rows, - `SELECT `+reviewMRTaskSelectCols+` FROM gitlab_review_mr_tasks ORDER BY created_at ASC`); err != nil { + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( + `SELECT `+reviewMRTaskSelectCols+` FROM gitlab_review_mr_tasks ORDER BY created_at ASC`)); err != nil { return nil, err } out := make([]*ReviewMRTask, 0, len(rows)) @@ -545,12 +545,12 @@ func (s *Store) ListAllReviewMRTasks(ctx context.Context) ([]*ReviewMRTask, erro func (s *Store) ListReviewMRTasksForWorkspace(ctx context.Context, workspaceID string) ([]*ReviewMRTask, error) { var rows []ReviewMRTask - if err := s.ro.SelectContext(ctx, &rows, + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( `SELECT t.id, t.review_watch_id, t.project_path, t.mr_iid, t.mr_url, t.task_id, t.generation, t.created_at FROM gitlab_review_mr_tasks t JOIN gitlab_review_watches w ON w.id = t.review_watch_id - WHERE w.workspace_id = ? ORDER BY t.created_at ASC`, workspaceID); err != nil { + WHERE w.workspace_id = ? ORDER BY t.created_at ASC`), workspaceID); err != nil { return nil, err } out := make([]*ReviewMRTask, 0, len(rows)) @@ -562,7 +562,7 @@ func (s *Store) ListReviewMRTasksForWorkspace(ctx context.Context, workspaceID s // DeleteReviewMRTask removes a dedup row by id. func (s *Store) DeleteReviewMRTask(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM gitlab_review_mr_tasks WHERE id = ?`, id) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM gitlab_review_mr_tasks WHERE id = ?`), id) return err } @@ -626,12 +626,12 @@ func (s *Store) GetIssueWatchIncludingDeleting(ctx context.Context, id string) ( func (s *Store) getIssueWatch(ctx context.Context, id string, includeDeleting bool) (*IssueWatch, error) { var iw IssueWatch - deletingClause := " AND deleting = 0" + deletingClause := " AND deleting = FALSE" if includeDeleting { deletingClause = "" } - err := s.ro.GetContext(ctx, &iw, - `SELECT `+issueWatchSelectCols+` FROM gitlab_issue_watches WHERE id = ?`+deletingClause, id) + err := s.ro.GetContext(ctx, &iw, s.ro.Rebind( + `SELECT `+issueWatchSelectCols+` FROM gitlab_issue_watches WHERE id = ?`+deletingClause), id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -648,31 +648,31 @@ func (s *Store) getIssueWatch(ctx context.Context, id string, includeDeleting bo func (s *Store) ListIssueWatches(ctx context.Context, workspaceID string) ([]*IssueWatch, error) { return s.listIssueWatches(ctx, `SELECT `+issueWatchSelectCols+` FROM gitlab_issue_watches - WHERE workspace_id = ? AND deleting = 0 ORDER BY created_at ASC`, workspaceID) + WHERE workspace_id = ? AND deleting = FALSE ORDER BY created_at ASC`, workspaceID) } // ListAllIssueWatches lists every issue watch. func (s *Store) ListAllIssueWatches(ctx context.Context) ([]*IssueWatch, error) { return s.listIssueWatches(ctx, - `SELECT `+issueWatchSelectCols+` FROM gitlab_issue_watches WHERE deleting = 0 ORDER BY created_at ASC`) + `SELECT `+issueWatchSelectCols+` FROM gitlab_issue_watches WHERE deleting = FALSE ORDER BY created_at ASC`) } // ListEnabledIssueWatches lists every enabled issue watch. func (s *Store) ListEnabledIssueWatches(ctx context.Context) ([]*IssueWatch, error) { return s.listIssueWatches(ctx, `SELECT `+issueWatchSelectCols+` FROM gitlab_issue_watches - WHERE enabled = 1 AND deleting = 0 ORDER BY created_at ASC`) + WHERE enabled = TRUE AND deleting = FALSE ORDER BY created_at ASC`) } func (s *Store) ListEnabledIssueWatchesForWorkspace(ctx context.Context, workspaceID string) ([]*IssueWatch, error) { return s.listIssueWatches(ctx, `SELECT `+issueWatchSelectCols+` FROM gitlab_issue_watches - WHERE enabled = 1 AND deleting = 0 AND workspace_id = ? ORDER BY created_at ASC`, workspaceID) + WHERE enabled = TRUE AND deleting = FALSE AND workspace_id = ? ORDER BY created_at ASC`, workspaceID) } func (s *Store) listIssueWatches(ctx context.Context, query string, args ...interface{}) ([]*IssueWatch, error) { var rows []IssueWatch - if err := s.ro.SelectContext(ctx, &rows, query, args...); err != nil { + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind(query), args...); err != nil { return nil, err } out := make([]*IssueWatch, 0, len(rows)) @@ -723,16 +723,16 @@ func (s *Store) UpdateIssueWatch(ctx context.Context, iw *IssueWatch) error { // RecordIssueWatchPoll stamps last_polled_at on the watch. func (s *Store) RecordIssueWatchPoll(ctx context.Context, id string, polledAt time.Time) error { - _, err := s.db.ExecContext(ctx, - `UPDATE gitlab_issue_watches SET last_polled_at = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE gitlab_issue_watches SET last_polled_at = ?, updated_at = ? WHERE id = ?`), polledAt, time.Now().UTC(), id) return err } func (s *Store) DisableIssueWatchWithError(ctx context.Context, id, cause string) error { now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, `UPDATE gitlab_issue_watches - SET enabled = 0, last_error = ?, last_error_at = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind(`UPDATE gitlab_issue_watches + SET enabled = FALSE, last_error = ?, last_error_at = ?, updated_at = ? WHERE id = ?`), cause, now, now, id) return err } @@ -744,10 +744,10 @@ func (s *Store) DeleteIssueWatch(ctx context.Context, id string) error { return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, `DELETE FROM gitlab_issue_watch_tasks WHERE issue_watch_id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(`DELETE FROM gitlab_issue_watch_tasks WHERE issue_watch_id = ?`), id); err != nil { return err } - if _, err := tx.ExecContext(ctx, `DELETE FROM gitlab_issue_watches WHERE id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, tx.Rebind(`DELETE FROM gitlab_issue_watches WHERE id = ?`), id); err != nil { return err } return tx.Commit() @@ -761,9 +761,9 @@ const issueWatchTaskSelectCols = `id, issue_watch_id, project_path, issue_iid, // HasIssueWatchTask reports whether the (watch, project, iid) is dedup-claimed. func (s *Store) HasIssueWatchTask(ctx context.Context, issueWatchID, projectPath string, iid int) (bool, error) { var count int - err := s.ro.GetContext(ctx, &count, + err := s.ro.GetContext(ctx, &count, s.ro.Rebind( `SELECT COUNT(*) FROM gitlab_issue_watch_tasks - WHERE issue_watch_id = ? AND project_path = ? AND issue_iid = ?`, + WHERE issue_watch_id = ? AND project_path = ? AND issue_iid = ?`), issueWatchID, projectPath, iid) if err != nil { return false, err @@ -797,11 +797,11 @@ func (s *Store) reserveIssueWatchTask(ctx context.Context, issueWatchID string, INSERT INTO gitlab_issue_watch_tasks (id, issue_watch_id, project_path, issue_iid, issue_url, task_id, generation, created_at) SELECT ?, ?, ?, ?, ?, '', ?, ? WHERE EXISTS (SELECT 1 FROM gitlab_issue_watches - WHERE id = ? AND generation = ? AND enabled = 1 AND deleting = 0) + WHERE id = ? AND generation = ? AND enabled = TRUE AND deleting = FALSE) ON CONFLICT(issue_watch_id, project_path, issue_iid) DO NOTHING` args = append(args, issueWatchID, generation) } - result, err := s.db.ExecContext(ctx, query, args...) + result, err := s.db.ExecContext(ctx, s.db.Rebind(query), args...) if err != nil { return false, err } @@ -826,15 +826,15 @@ func (s *Store) assignIssueWatchTaskID(ctx context.Context, issueWatchID string, activeClause := "" if requireActive { activeClause = ` AND EXISTS (SELECT 1 FROM gitlab_issue_watches - WHERE id = ? AND generation = ? AND enabled = 1 AND deleting = 0)` + WHERE id = ? AND generation = ? AND enabled = TRUE AND deleting = FALSE)` } args := []interface{}{taskID, issueWatchID, projectPath, iid, generation} if requireActive { args = append(args, issueWatchID, generation) } - res, err := s.db.ExecContext(ctx, ` + res, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE gitlab_issue_watch_tasks SET task_id = ? - WHERE issue_watch_id = ? AND project_path = ? AND issue_iid = ? AND generation = ?`+activeClause, + WHERE issue_watch_id = ? AND project_path = ? AND issue_iid = ? AND generation = ?`+activeClause), args...) if err != nil { return err @@ -851,25 +851,25 @@ func (s *Store) assignIssueWatchTaskID(ctx context.Context, issueWatchID string, // ReleaseIssueWatchTask removes a failed reservation. func (s *Store) ReleaseIssueWatchTask(ctx context.Context, issueWatchID, projectPath string, iid int) error { - _, err := s.db.ExecContext(ctx, + _, err := s.db.ExecContext(ctx, s.db.Rebind( `DELETE FROM gitlab_issue_watch_tasks - WHERE issue_watch_id = ? AND project_path = ? AND issue_iid = ?`, + WHERE issue_watch_id = ? AND project_path = ? AND issue_iid = ?`), issueWatchID, projectPath, iid) return err } func (s *Store) ReleaseIssueWatchTaskForGeneration(ctx context.Context, issueWatchID string, generation int64, projectPath string, iid int) error { - _, err := s.db.ExecContext(ctx, + _, err := s.db.ExecContext(ctx, s.db.Rebind( `DELETE FROM gitlab_issue_watch_tasks - WHERE issue_watch_id = ? AND project_path = ? AND issue_iid = ? AND generation = ?`, + WHERE issue_watch_id = ? AND project_path = ? AND issue_iid = ? AND generation = ?`), issueWatchID, projectPath, iid, generation) return err } func (s *Store) issueWatchGeneration(ctx context.Context, watchID string) (int64, error) { var generation int64 - if err := s.ro.GetContext(ctx, &generation, - `SELECT generation FROM gitlab_issue_watches WHERE id = ?`, watchID); err != nil { + if err := s.ro.GetContext(ctx, &generation, s.ro.Rebind( + `SELECT generation FROM gitlab_issue_watches WHERE id = ?`), watchID); err != nil { if errors.Is(err, sql.ErrNoRows) { return 1, nil } @@ -881,9 +881,9 @@ func (s *Store) issueWatchGeneration(ctx context.Context, watchID string) (int64 // ListIssueWatchTasksByWatch lists dedup rows for an issue watch. func (s *Store) ListIssueWatchTasksByWatch(ctx context.Context, watchID string) ([]*IssueWatchTask, error) { var rows []IssueWatchTask - if err := s.ro.SelectContext(ctx, &rows, + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( `SELECT `+issueWatchTaskSelectCols+` FROM gitlab_issue_watch_tasks - WHERE issue_watch_id = ? ORDER BY created_at ASC`, watchID); err != nil { + WHERE issue_watch_id = ? ORDER BY created_at ASC`), watchID); err != nil { return nil, err } out := make([]*IssueWatchTask, 0, len(rows)) @@ -896,8 +896,8 @@ func (s *Store) ListIssueWatchTasksByWatch(ctx context.Context, watchID string) // ListAllIssueWatchTasks returns every dedup row. func (s *Store) ListAllIssueWatchTasks(ctx context.Context) ([]*IssueWatchTask, error) { var rows []IssueWatchTask - if err := s.ro.SelectContext(ctx, &rows, - `SELECT `+issueWatchTaskSelectCols+` FROM gitlab_issue_watch_tasks ORDER BY created_at ASC`); err != nil { + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( + `SELECT `+issueWatchTaskSelectCols+` FROM gitlab_issue_watch_tasks ORDER BY created_at ASC`)); err != nil { return nil, err } out := make([]*IssueWatchTask, 0, len(rows)) @@ -909,12 +909,12 @@ func (s *Store) ListAllIssueWatchTasks(ctx context.Context) ([]*IssueWatchTask, func (s *Store) ListIssueWatchTasksForWorkspace(ctx context.Context, workspaceID string) ([]*IssueWatchTask, error) { var rows []IssueWatchTask - if err := s.ro.SelectContext(ctx, &rows, + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( `SELECT t.id, t.issue_watch_id, t.project_path, t.issue_iid, t.issue_url, t.task_id, t.generation, t.created_at FROM gitlab_issue_watch_tasks t JOIN gitlab_issue_watches w ON w.id = t.issue_watch_id - WHERE w.workspace_id = ? ORDER BY t.created_at ASC`, workspaceID); err != nil { + WHERE w.workspace_id = ? ORDER BY t.created_at ASC`), workspaceID); err != nil { return nil, err } out := make([]*IssueWatchTask, 0, len(rows)) @@ -926,7 +926,7 @@ func (s *Store) ListIssueWatchTasksForWorkspace(ctx context.Context, workspaceID // DeleteIssueWatchTask removes a dedup row by id. func (s *Store) DeleteIssueWatchTask(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, `DELETE FROM gitlab_issue_watch_tasks WHERE id = ?`, id) + _, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM gitlab_issue_watch_tasks WHERE id = ?`), id) return err } @@ -941,9 +941,9 @@ func (s *Store) GetActionPresets(ctx context.Context, workspaceID string) (*Acti IssuePresets string `db:"issue_presets"` UpdatedAt time.Time `db:"updated_at"` } - err := s.ro.GetContext(ctx, &row, + err := s.ro.GetContext(ctx, &row, s.ro.Rebind( `SELECT workspace_id, mr_presets, issue_presets, updated_at - FROM gitlab_action_presets WHERE workspace_id = ?`, workspaceID) + FROM gitlab_action_presets WHERE workspace_id = ?`), workspaceID) if errors.Is(err, sql.ErrNoRows) { return &ActionPresets{WorkspaceID: workspaceID}, nil } @@ -971,21 +971,21 @@ func (s *Store) UpsertActionPresets(ctx context.Context, presets *ActionPresets) return fmt.Errorf("encode issue_presets: %w", err) } now := time.Now().UTC() - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO gitlab_action_presets (workspace_id, mr_presets, issue_presets, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(workspace_id) DO UPDATE SET mr_presets = excluded.mr_presets, issue_presets = excluded.issue_presets, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), presets.WorkspaceID, string(mrJSON), string(issueJSON), now) return err } // DeleteActionPresets resets a workspace to the default presets. func (s *Store) DeleteActionPresets(ctx context.Context, workspaceID string) error { - _, err := s.db.ExecContext(ctx, - `DELETE FROM gitlab_action_presets WHERE workspace_id = ?`, workspaceID) + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `DELETE FROM gitlab_action_presets WHERE workspace_id = ?`), workspaceID) return err } diff --git a/apps/backend/internal/jira/store.go b/apps/backend/internal/jira/store.go index da37771c7f..ba30b9b4ae 100644 --- a/apps/backend/internal/jira/store.go +++ b/apps/backend/internal/jira/store.go @@ -5,11 +5,14 @@ import ( "database/sql" "errors" "fmt" + "strings" "time" "github.com/google/uuid" "github.com/jmoiron/sqlx" + dbutil "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/db/dialect" "github.com/kandev/kandev/internal/integrations/workspacescope" ) @@ -106,7 +109,7 @@ func (s *Store) initSchema() error { if err := s.migrateLegacySingletonTable(); err != nil { return err } - if _, err := s.db.Exec(createTablesSQL); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(createTablesSQL, s.db.DriverName())); err != nil { return err } if err := s.addInstanceTypeColumn(); err != nil { @@ -139,17 +142,17 @@ func (s *Store) addConfigHealthColumns() error { return nil } if _, ok := cols["last_checked_at"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE jira_configs ADD COLUMN last_checked_at DATETIME`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE jira_configs ADD COLUMN last_checked_at DATETIME`, s.db.DriverName())); err != nil { return fmt.Errorf("add last_checked_at column: %w", err) } } if _, ok := cols["last_ok"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE jira_configs ADD COLUMN last_ok INTEGER NOT NULL DEFAULT 0`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE jira_configs ADD COLUMN last_ok INTEGER NOT NULL DEFAULT 0`, s.db.DriverName())); err != nil { return fmt.Errorf("add last_ok column: %w", err) } } if _, ok := cols["last_error"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE jira_configs ADD COLUMN last_error TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE jira_configs ADD COLUMN last_error TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add last_error column: %w", err) } } @@ -170,12 +173,12 @@ func (s *Store) addIssueWatchRepositoryColumns() error { return nil } if _, ok := cols["repository_id"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE jira_issue_watches ADD COLUMN repository_id TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE jira_issue_watches ADD COLUMN repository_id TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add repository_id column: %w", err) } } if _, ok := cols["base_branch"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE jira_issue_watches ADD COLUMN base_branch TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE jira_issue_watches ADD COLUMN base_branch TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add base_branch column: %w", err) } } @@ -197,7 +200,7 @@ func (s *Store) addMaxInflightTasksColumn() error { if _, ok := cols["max_inflight_tasks"]; ok { return nil } - if _, err := s.db.Exec(`ALTER TABLE jira_issue_watches ADD COLUMN max_inflight_tasks INTEGER DEFAULT 5`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE jira_issue_watches ADD COLUMN max_inflight_tasks INTEGER DEFAULT 5`, s.db.DriverName())); err != nil { return fmt.Errorf("add max_inflight_tasks column: %w", err) } return nil @@ -213,12 +216,12 @@ func (s *Store) addIssueWatchLastErrorColumns() error { return err } if _, ok := cols["last_error"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE jira_issue_watches ADD COLUMN last_error TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE jira_issue_watches ADD COLUMN last_error TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add last_error column: %w", err) } } if _, ok := cols["last_error_at"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE jira_issue_watches ADD COLUMN last_error_at DATETIME`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE jira_issue_watches ADD COLUMN last_error_at DATETIME`, s.db.DriverName())); err != nil { return fmt.Errorf("add last_error_at column: %w", err) } } @@ -238,7 +241,7 @@ func (s *Store) addInstanceTypeColumn() error { if _, ok := cols["instance_type"]; ok { return nil } - if _, err := s.db.Exec(`ALTER TABLE jira_configs ADD COLUMN instance_type TEXT NOT NULL DEFAULT 'cloud'`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE jira_configs ADD COLUMN instance_type TEXT NOT NULL DEFAULT 'cloud'`, s.db.DriverName())); err != nil { return fmt.Errorf("add instance_type column: %w", err) } return nil @@ -253,17 +256,17 @@ func (s *Store) addOAuthColumns() error { return err } if _, ok := cols["client_id"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE jira_configs ADD COLUMN client_id TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE jira_configs ADD COLUMN client_id TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add client_id column: %w", err) } } if _, ok := cols["cloud_id"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE jira_configs ADD COLUMN cloud_id TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE jira_configs ADD COLUMN cloud_id TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add cloud_id column: %w", err) } } if _, ok := cols["token_expires_at"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE jira_configs ADD COLUMN token_expires_at DATETIME`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE jira_configs ADD COLUMN token_expires_at DATETIME`, s.db.DriverName())); err != nil { return fmt.Errorf("add token_expires_at column: %w", err) } } @@ -274,6 +277,9 @@ func (s *Store) addOAuthColumns() error { // rewrites it into the workspace-scoped shape. Picks the active/default // workspace as the target so startup is deterministic. func (s *Store) migrateLegacySingletonTable() error { + if dialect.IsPostgres(s.db.DriverName()) { + return nil + } cols, err := s.tableColumns("jira_configs") if err != nil { return err @@ -377,27 +383,27 @@ func nullableTime(t sql.NullTime) interface{} { } func (s *Store) tableColumns(table string) (map[string]struct{}, error) { - rows, err := s.db.Query(fmt.Sprintf("PRAGMA table_info(%s)", table)) + columns, err := dbutil.TableColumns(s.db, table) if err != nil { return nil, err } - defer func() { _ = rows.Close() }() - cols := make(map[string]struct{}) - for rows.Next() { - var ( - cid int - name string - ctype string - notnull int - dflt sql.NullString - pk int - ) - if err := rows.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk); err != nil { - return nil, err - } + cols := make(map[string]struct{}, len(columns)) + for name := range columns { cols[name] = struct{}{} } - return cols, rows.Err() + return cols, nil +} + +func schemaSQLForDriver(schema, driver string) string { + schema = strings.ReplaceAll(schema, "TIMESTAMP", dialect.TimestampType(driver)) + schema = strings.ReplaceAll(schema, "DATETIME", dialect.TimestampType(driver)) + if dialect.IsPostgres(driver) { + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 1", "BOOLEAN NOT NULL DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 0", "BOOLEAN NOT NULL DEFAULT FALSE") + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 1", "BOOLEAN DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 0", "BOOLEAN DEFAULT FALSE") + } + return schema } const selectConfigColumns = `workspace_id, site_url, email, auth_method, instance_type, default_project_key, @@ -422,8 +428,8 @@ func (s *Store) GetConfigForWorkspace(ctx context.Context, workspaceID string) ( return nil, err } var cfg JiraConfig - err = s.ro.GetContext(ctx, &cfg, - `SELECT `+selectConfigColumns+` FROM jira_configs WHERE workspace_id = ?`, workspaceID) + err = s.ro.GetContext(ctx, &cfg, s.ro.Rebind( + `SELECT `+selectConfigColumns+` FROM jira_configs WHERE workspace_id = ?`), workspaceID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -462,7 +468,7 @@ func (s *Store) UpsertConfigForWorkspace(ctx context.Context, workspaceID string if cfg.InstanceType == "" { cfg.InstanceType = InstanceTypeCloud } - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO jira_configs (workspace_id, site_url, email, auth_method, instance_type, default_project_key, client_id, cloud_id, token_expires_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) @@ -475,7 +481,7 @@ func (s *Store) UpsertConfigForWorkspace(ctx context.Context, workspaceID string client_id = excluded.client_id, cloud_id = excluded.cloud_id, token_expires_at = excluded.token_expires_at, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), workspaceID, cfg.SiteURL, cfg.Email, cfg.AuthMethod, cfg.InstanceType, cfg.DefaultProjectKey, cfg.ClientID, cfg.CloudID, cfg.TokenExpiresAt, cfg.CreatedAt, cfg.UpdatedAt) return err @@ -497,7 +503,7 @@ func (s *Store) DeleteConfigForWorkspace(ctx context.Context, workspaceID string if err != nil { return err } - _, err = s.db.ExecContext(ctx, `DELETE FROM jira_configs WHERE workspace_id = ?`, workspaceID) + _, err = s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM jira_configs WHERE workspace_id = ?`), workspaceID) return err } @@ -505,8 +511,7 @@ func (s *Store) DeleteConfigForWorkspace(ctx context.Context, workspaceID string // poller to decide whether to probe at all. func (s *Store) HasConfig(ctx context.Context) (bool, error) { var present int - err := s.ro.GetContext(ctx, &present, - `SELECT COUNT(*) FROM jira_configs`) + err := s.ro.GetContext(ctx, &present, s.ro.Rebind(`SELECT COUNT(*) FROM jira_configs`)) if err != nil { return false, err } @@ -516,7 +521,7 @@ func (s *Store) HasConfig(ctx context.Context) (bool, error) { // ListConfigWorkspaceIDs returns every workspace with a saved Jira config. func (s *Store) ListConfigWorkspaceIDs(ctx context.Context) ([]string, error) { var ids []string - if err := s.ro.SelectContext(ctx, &ids, `SELECT workspace_id FROM jira_configs ORDER BY workspace_id`); err != nil { + if err := s.ro.SelectContext(ctx, &ids, s.ro.Rebind(`SELECT workspace_id FROM jira_configs ORDER BY workspace_id`)); err != nil { return nil, err } return ids, nil @@ -541,10 +546,10 @@ func (s *Store) UpdateAuthHealthForWorkspace(ctx context.Context, workspaceID st if err != nil { return err } - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` UPDATE jira_configs - SET last_checked_at = ?, last_ok = ?, last_error = ? - WHERE workspace_id = ?`, + SET last_checked_at = ?, last_ok = CASE WHEN ? THEN 1 ELSE 0 END, last_error = ? + WHERE workspace_id = ?`), checkedAt, ok, errMsg, workspaceID) return err } @@ -556,8 +561,8 @@ func (s *Store) UpdateTokenExpiryForWorkspace(ctx context.Context, workspaceID s if err != nil { return err } - _, err = s.db.ExecContext(ctx, ` - UPDATE jira_configs SET token_expires_at = ?, updated_at = ? WHERE workspace_id = ?`, + _, err = s.db.ExecContext(ctx, s.db.Rebind(` + UPDATE jira_configs SET token_expires_at = ?, updated_at = ? WHERE workspace_id = ?`), expiresAt, time.Now().UTC(), workspaceID) return err } @@ -614,9 +619,9 @@ func (s *Store) CreateIssueWatch(ctx context.Context, w *IssueWatch) error { if w.PollIntervalSeconds <= 0 { w.PollIntervalSeconds = DefaultIssueWatchPollInterval } - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO jira_issue_watches (`+issueWatchInsertColumns+`) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`), w.ID, w.WorkspaceID, w.WorkflowID, w.WorkflowStepID, w.RepositoryID, w.BaseBranch, w.JQL, w.AgentProfileID, w.ExecutorProfileID, w.Prompt, w.Enabled, @@ -629,8 +634,8 @@ func (s *Store) CreateIssueWatch(ctx context.Context, w *IssueWatch) error { // GetIssueWatch returns a single watch by ID, or nil when no row matches. func (s *Store) GetIssueWatch(ctx context.Context, id string) (*IssueWatch, error) { var w IssueWatch - err := s.ro.GetContext(ctx, &w, - `SELECT `+issueWatchSelectColumns+` FROM jira_issue_watches WHERE id = ?`, id) + err := s.ro.GetContext(ctx, &w, s.ro.Rebind( + `SELECT `+issueWatchSelectColumns+` FROM jira_issue_watches WHERE id = ?`), id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -644,9 +649,9 @@ func (s *Store) GetIssueWatch(ctx context.Context, id string) (*IssueWatch, erro // insertion order. The UI uses this to render the watcher table. func (s *Store) ListIssueWatches(ctx context.Context, workspaceID string) ([]*IssueWatch, error) { var watches []*IssueWatch - err := s.ro.SelectContext(ctx, &watches, + err := s.ro.SelectContext(ctx, &watches, s.ro.Rebind( `SELECT `+issueWatchSelectColumns+` FROM jira_issue_watches - WHERE workspace_id = ? ORDER BY created_at`, workspaceID) + WHERE workspace_id = ? ORDER BY created_at`), workspaceID) if err != nil { return nil, err } @@ -659,8 +664,8 @@ func (s *Store) ListIssueWatches(ctx context.Context, workspaceID string) ([]*Is // watches without first picking a workspace context. func (s *Store) ListAllIssueWatches(ctx context.Context) ([]*IssueWatch, error) { var watches []*IssueWatch - err := s.ro.SelectContext(ctx, &watches, - `SELECT `+issueWatchSelectColumns+` FROM jira_issue_watches ORDER BY workspace_id, created_at`) + err := s.ro.SelectContext(ctx, &watches, s.ro.Rebind( + `SELECT `+issueWatchSelectColumns+` FROM jira_issue_watches ORDER BY workspace_id, created_at`)) if err != nil { return nil, err } @@ -671,9 +676,9 @@ func (s *Store) ListAllIssueWatches(ctx context.Context) ([]*IssueWatch, error) // used by the poller to decide what to query each tick. func (s *Store) ListEnabledIssueWatches(ctx context.Context) ([]*IssueWatch, error) { var watches []*IssueWatch - err := s.ro.SelectContext(ctx, &watches, + err := s.ro.SelectContext(ctx, &watches, s.ro.Rebind( `SELECT `+issueWatchSelectColumns+` FROM jira_issue_watches - WHERE enabled = 1 ORDER BY created_at`) + WHERE enabled = TRUE ORDER BY created_at`)) if err != nil { return nil, err } @@ -688,13 +693,13 @@ func (s *Store) UpdateIssueWatch(ctx context.Context, w *IssueWatch) error { if w.PollIntervalSeconds <= 0 { w.PollIntervalSeconds = DefaultIssueWatchPollInterval } - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE jira_issue_watches SET workflow_id = ?, workflow_step_id = ?, repository_id = ?, base_branch = ?, jql = ?, agent_profile_id = ?, executor_profile_id = ?, prompt = ?, enabled = ?, poll_interval_seconds = ?, max_inflight_tasks = ?, last_polled_at = ?, updated_at = ? - WHERE id = ?`, + WHERE id = ?`), w.WorkflowID, w.WorkflowStepID, w.RepositoryID, w.BaseBranch, w.JQL, w.AgentProfileID, w.ExecutorProfileID, w.Prompt, @@ -707,8 +712,8 @@ func (s *Store) UpdateIssueWatch(ctx context.Context, w *IssueWatch) error { // the rest of the row. The poller calls this after every check so the UI can // show "polled X seconds ago". func (s *Store) UpdateIssueWatchLastPolled(ctx context.Context, id string, t time.Time) error { - _, err := s.db.ExecContext(ctx, - `UPDATE jira_issue_watches SET last_polled_at = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE jira_issue_watches SET last_polled_at = ?, updated_at = ? WHERE id = ?`), t, time.Now().UTC(), id) return err } @@ -720,10 +725,10 @@ func (s *Store) UpdateIssueWatchLastPolled(ctx context.Context, id string, t tim // soft-deleted. func (s *Store) DisableIssueWatchWithError(ctx context.Context, id, cause string) error { now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, + _, err := s.db.ExecContext(ctx, s.db.Rebind( `UPDATE jira_issue_watches - SET enabled = 0, last_error = ?, last_error_at = ?, updated_at = ? - WHERE id = ?`, + SET enabled = FALSE, last_error = ?, last_error_at = ?, updated_at = ? + WHERE id = ?`), cause, now, now, id) return err } @@ -737,10 +742,10 @@ func (s *Store) DeleteIssueWatch(ctx context.Context, id string) error { return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, `DELETE FROM jira_issue_watch_tasks WHERE issue_watch_id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind(`DELETE FROM jira_issue_watch_tasks WHERE issue_watch_id = ?`), id); err != nil { return err } - if _, err := tx.ExecContext(ctx, `DELETE FROM jira_issue_watches WHERE id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind(`DELETE FROM jira_issue_watches WHERE id = ?`), id); err != nil { return err } return tx.Commit() @@ -751,9 +756,10 @@ func (s *Store) DeleteIssueWatch(ctx context.Context, id string) error { // proceed to create the task. False either means another handler already // reserved the same ticket or the row already exists from a prior run. func (s *Store) ReserveIssueWatchTask(ctx context.Context, watchID, issueKey, issueURL string) (bool, error) { - res, err := s.db.ExecContext(ctx, ` - INSERT OR IGNORE INTO jira_issue_watch_tasks (id, issue_watch_id, issue_key, issue_url, task_id, created_at) - VALUES (?, ?, ?, ?, ?, ?)`, + res, err := s.db.ExecContext(ctx, s.db.Rebind(` + INSERT INTO jira_issue_watch_tasks (id, issue_watch_id, issue_key, issue_url, task_id, created_at) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(issue_watch_id, issue_key) DO NOTHING`), uuid.New().String(), watchID, issueKey, issueURL, "", time.Now().UTC()) if err != nil { return false, err @@ -770,9 +776,9 @@ func (s *Store) ReserveIssueWatchTask(ctx context.Context, watchID, issueKey, is // that as a programming bug since they only call this after a successful // reservation. func (s *Store) AssignIssueWatchTaskID(ctx context.Context, watchID, issueKey, taskID string) error { - res, err := s.db.ExecContext(ctx, ` + res, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE jira_issue_watch_tasks SET task_id = ? - WHERE issue_watch_id = ? AND issue_key = ?`, + WHERE issue_watch_id = ? AND issue_key = ?`), taskID, watchID, issueKey) if err != nil { return err @@ -790,8 +796,8 @@ func (s *Store) AssignIssueWatchTaskID(ctx context.Context, watchID, issueKey, t // ReleaseIssueWatchTask drops a reservation so the next poll can retry. Used // when task creation fails after a successful reserve. func (s *Store) ReleaseIssueWatchTask(ctx context.Context, watchID, issueKey string) error { - _, err := s.db.ExecContext(ctx, - `DELETE FROM jira_issue_watch_tasks WHERE issue_watch_id = ? AND issue_key = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `DELETE FROM jira_issue_watch_tasks WHERE issue_watch_id = ? AND issue_key = ?`), watchID, issueKey) return err } @@ -802,8 +808,8 @@ func (s *Store) ReleaseIssueWatchTask(ctx context.Context, watchID, issueKey str // per-call savings scale with the workspace's watch count. func (s *Store) ListSeenIssueKeys(ctx context.Context, watchID string) (map[string]struct{}, error) { var keys []string - err := s.ro.SelectContext(ctx, &keys, - `SELECT issue_key FROM jira_issue_watch_tasks WHERE issue_watch_id = ?`, watchID) + err := s.ro.SelectContext(ctx, &keys, s.ro.Rebind( + `SELECT issue_key FROM jira_issue_watch_tasks WHERE issue_watch_id = ?`), watchID) if err != nil { return nil, err } @@ -819,8 +825,8 @@ func (s *Store) ListSeenIssueKeys(ctx context.Context, watchID string) (map[stri // Used by the reset flow to enumerate the tasks to cascade-delete. func (s *Store) ListIssueWatchTaskIDs(ctx context.Context, watchID string) ([]string, error) { var ids []string - err := s.ro.SelectContext(ctx, &ids, - `SELECT task_id FROM jira_issue_watch_tasks WHERE issue_watch_id = ?`, watchID) + err := s.ro.SelectContext(ctx, &ids, s.ro.Rebind( + `SELECT task_id FROM jira_issue_watch_tasks WHERE issue_watch_id = ?`), watchID) return ids, err } @@ -834,12 +840,12 @@ func (s *Store) ResetIssueWatchState(ctx context.Context, watchID string) error return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, - `DELETE FROM jira_issue_watch_tasks WHERE issue_watch_id = ?`, watchID); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind( + `DELETE FROM jira_issue_watch_tasks WHERE issue_watch_id = ?`), watchID); err != nil { return err } - if _, err := tx.ExecContext(ctx, - `UPDATE jira_issue_watches SET last_polled_at = NULL, updated_at = ? WHERE id = ?`, + if _, err := tx.ExecContext(ctx, s.db.Rebind( + `UPDATE jira_issue_watches SET last_polled_at = NULL, updated_at = ? WHERE id = ?`), time.Now().UTC(), watchID); err != nil { return err } diff --git a/apps/backend/internal/jira/store_postgres_test.go b/apps/backend/internal/jira/store_postgres_test.go new file mode 100644 index 0000000000..c401b5758c --- /dev/null +++ b/apps/backend/internal/jira/store_postgres_test.go @@ -0,0 +1,74 @@ +package jira + +import ( + "context" + "testing" + "time" + + "github.com/kandev/kandev/internal/testutil" +) + +func TestPostgresStoreSchemaReplay(t *testing.T) { + ctx := context.Background() + database := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t)) + + store, err := NewStore(database, database) + if err != nil { + t.Fatalf("first Jira store schema init: %v", err) + } + if _, err := NewStore(database, database); err != nil { + t.Fatalf("second Jira store schema init: %v", err) + } + + config := &JiraConfig{ + SiteURL: "https://jira.example.com", + Email: "alice@example.com", + AuthMethod: AuthMethodAPIToken, + } + if err := store.UpsertConfigForWorkspace(ctx, "ws-1", config); err != nil { + t.Fatalf("upsert Jira config: %v", err) + } + gotConfig, err := store.GetConfigForWorkspace(ctx, "ws-1") + if err != nil || gotConfig == nil || gotConfig.SiteURL != config.SiteURL { + t.Fatalf("get Jira config: config=%+v err=%v", gotConfig, err) + } + if err := store.UpdateAuthHealthForWorkspace(ctx, "ws-1", true, "", time.Now().UTC()); err != nil { + t.Fatalf("update Jira auth health: %v", err) + } + + watch := &IssueWatch{ + WorkspaceID: "ws-1", + WorkflowID: "workflow-1", + WorkflowStepID: "step-1", + JQL: "project = ENG", + AgentProfileID: "agent-1", + ExecutorProfileID: "executor-1", + Enabled: true, + } + if err := store.CreateIssueWatch(ctx, watch); err != nil { + t.Fatalf("create Jira issue watch: %v", err) + } + gotWatch, err := store.GetIssueWatch(ctx, watch.ID) + if err != nil || gotWatch == nil || gotWatch.JQL != watch.JQL { + t.Fatalf("get Jira issue watch: watch=%+v err=%v", gotWatch, err) + } + if enabled, err := store.ListEnabledIssueWatches(ctx); err != nil || len(enabled) != 1 { + t.Fatalf("list enabled Jira issue watches: watches=%d err=%v", len(enabled), err) + } + + reserved, err := store.ReserveIssueWatchTask(ctx, watch.ID, "ENG-123", "https://jira.example.com/browse/ENG-123") + if err != nil || !reserved { + t.Fatalf("reserve Jira issue: reserved=%v err=%v", reserved, err) + } + reserved, err = store.ReserveIssueWatchTask(ctx, watch.ID, "ENG-123", "https://jira.example.com/browse/ENG-123") + if err != nil || reserved { + t.Fatalf("duplicate Jira issue reservation: reserved=%v err=%v", reserved, err) + } + if err := store.AssignIssueWatchTaskID(ctx, watch.ID, "ENG-123", "task-1"); err != nil { + t.Fatalf("assign Jira issue task: %v", err) + } + seen, err := store.ListSeenIssueKeys(ctx, watch.ID) + if err != nil || len(seen) != 1 { + t.Fatalf("list Jira seen issues: seen=%d err=%v", len(seen), err) + } +} diff --git a/apps/backend/internal/linear/store.go b/apps/backend/internal/linear/store.go index a06593e101..034824cf91 100644 --- a/apps/backend/internal/linear/store.go +++ b/apps/backend/internal/linear/store.go @@ -5,10 +5,13 @@ import ( "database/sql" "errors" "fmt" + "strings" "time" "github.com/jmoiron/sqlx" + dbutil "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/db/dialect" "github.com/kandev/kandev/internal/integrations/workspacescope" ) @@ -106,7 +109,7 @@ func (s *Store) initSchema() error { if err := s.migrateLegacySingletonTable(); err != nil { return err } - if _, err := s.db.Exec(createTablesSQL); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(createTablesSQL, s.db.DriverName())); err != nil { return err } if err := s.addConfigColumns(); err != nil { @@ -138,22 +141,22 @@ func (s *Store) addConfigColumns() error { return nil } if _, ok := cols["org_slug"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE linear_configs ADD COLUMN org_slug TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE linear_configs ADD COLUMN org_slug TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add org_slug column: %w", err) } } if _, ok := cols["last_checked_at"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE linear_configs ADD COLUMN last_checked_at DATETIME`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE linear_configs ADD COLUMN last_checked_at DATETIME`, s.db.DriverName())); err != nil { return fmt.Errorf("add last_checked_at column: %w", err) } } if _, ok := cols["last_ok"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE linear_configs ADD COLUMN last_ok INTEGER NOT NULL DEFAULT 0`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE linear_configs ADD COLUMN last_ok INTEGER NOT NULL DEFAULT 0`, s.db.DriverName())); err != nil { return fmt.Errorf("add last_ok column: %w", err) } } if _, ok := cols["last_error"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE linear_configs ADD COLUMN last_error TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE linear_configs ADD COLUMN last_error TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add last_error column: %w", err) } } @@ -175,12 +178,12 @@ func (s *Store) addIssueWatchRepositoryColumns() error { return nil } if _, ok := cols["repository_id"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE linear_issue_watches ADD COLUMN repository_id TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE linear_issue_watches ADD COLUMN repository_id TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add repository_id column: %w", err) } } if _, ok := cols["base_branch"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE linear_issue_watches ADD COLUMN base_branch TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE linear_issue_watches ADD COLUMN base_branch TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add base_branch column: %w", err) } } @@ -202,7 +205,7 @@ func (s *Store) addMaxInflightTasksColumn() error { if _, ok := cols["max_inflight_tasks"]; ok { return nil } - if _, err := s.db.Exec(`ALTER TABLE linear_issue_watches ADD COLUMN max_inflight_tasks INTEGER DEFAULT 5`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE linear_issue_watches ADD COLUMN max_inflight_tasks INTEGER DEFAULT 5`, s.db.DriverName())); err != nil { return fmt.Errorf("add max_inflight_tasks column: %w", err) } return nil @@ -223,7 +226,7 @@ func (s *Store) addIssueWatchSortByColumn() error { if _, ok := cols["sort_by"]; ok { return nil } - if _, err := s.db.Exec(`ALTER TABLE linear_issue_watches ADD COLUMN sort_by TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE linear_issue_watches ADD COLUMN sort_by TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add sort_by column: %w", err) } return nil @@ -240,12 +243,12 @@ func (s *Store) addIssueWatchLastErrorColumns() error { return err } if _, ok := cols["last_error"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE linear_issue_watches ADD COLUMN last_error TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE linear_issue_watches ADD COLUMN last_error TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add last_error column: %w", err) } } if _, ok := cols["last_error_at"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE linear_issue_watches ADD COLUMN last_error_at DATETIME`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE linear_issue_watches ADD COLUMN last_error_at DATETIME`, s.db.DriverName())); err != nil { return fmt.Errorf("add last_error_at column: %w", err) } } @@ -256,6 +259,9 @@ func (s *Store) addIssueWatchLastErrorColumns() error { // rewrites it into the workspace-scoped shape. Picks the active/default // workspace as the target so startup is deterministic. func (s *Store) migrateLegacySingletonTable() error { + if dialect.IsPostgres(s.db.DriverName()) { + return nil + } cols, err := s.tableColumns("linear_configs") if err != nil { return err @@ -367,27 +373,27 @@ func nullableTime(t sql.NullTime) interface{} { } func (s *Store) tableColumns(table string) (map[string]struct{}, error) { - rows, err := s.db.Query(fmt.Sprintf("PRAGMA table_info(%s)", table)) + columns, err := dbutil.TableColumns(s.db, table) if err != nil { return nil, err } - defer func() { _ = rows.Close() }() - cols := make(map[string]struct{}) - for rows.Next() { - var ( - cid int - name string - ctype string - notnull int - dflt sql.NullString - pk int - ) - if err := rows.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk); err != nil { - return nil, err - } + cols := make(map[string]struct{}, len(columns)) + for name := range columns { cols[name] = struct{}{} } - return cols, rows.Err() + return cols, nil +} + +func schemaSQLForDriver(schema, driver string) string { + schema = strings.ReplaceAll(schema, "TIMESTAMP", dialect.TimestampType(driver)) + schema = strings.ReplaceAll(schema, "DATETIME", dialect.TimestampType(driver)) + if dialect.IsPostgres(driver) { + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 1", "BOOLEAN NOT NULL DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 0", "BOOLEAN NOT NULL DEFAULT FALSE") + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 1", "BOOLEAN DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 0", "BOOLEAN DEFAULT FALSE") + } + return schema } const selectConfigColumns = `workspace_id, auth_method, default_team_key, org_slug, @@ -411,8 +417,8 @@ func (s *Store) GetConfigForWorkspace(ctx context.Context, workspaceID string) ( return nil, err } var cfg LinearConfig - err = s.ro.GetContext(ctx, &cfg, - `SELECT `+selectConfigColumns+` FROM linear_configs WHERE workspace_id = ?`, workspaceID) + err = s.ro.GetContext(ctx, &cfg, s.ro.Rebind( + `SELECT `+selectConfigColumns+` FROM linear_configs WHERE workspace_id = ?`), workspaceID) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -444,13 +450,13 @@ func (s *Store) UpsertConfigForWorkspace(ctx context.Context, workspaceID string cfg.CreatedAt = now } cfg.UpdatedAt = now - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO linear_configs (workspace_id, auth_method, default_team_key, created_at, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(workspace_id) DO UPDATE SET auth_method = excluded.auth_method, default_team_key = excluded.default_team_key, - updated_at = excluded.updated_at`, + updated_at = excluded.updated_at`), workspaceID, cfg.AuthMethod, cfg.DefaultTeamKey, cfg.CreatedAt, cfg.UpdatedAt) return err } @@ -470,7 +476,7 @@ func (s *Store) DeleteConfigForWorkspace(ctx context.Context, workspaceID string if err != nil { return err } - _, err = s.db.ExecContext(ctx, `DELETE FROM linear_configs WHERE workspace_id = ?`, workspaceID) + _, err = s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM linear_configs WHERE workspace_id = ?`), workspaceID) return err } @@ -478,8 +484,7 @@ func (s *Store) DeleteConfigForWorkspace(ctx context.Context, workspaceID string // poller to decide whether to probe at all. func (s *Store) HasConfig(ctx context.Context) (bool, error) { var present int - err := s.ro.GetContext(ctx, &present, - `SELECT COUNT(*) FROM linear_configs`) + err := s.ro.GetContext(ctx, &present, s.ro.Rebind(`SELECT COUNT(*) FROM linear_configs`)) if err != nil { return false, err } @@ -493,8 +498,8 @@ func (s *Store) HasConfigForWorkspace(ctx context.Context, workspaceID string) ( return false, err } var present int - err = s.ro.GetContext(ctx, &present, - `SELECT COUNT(*) FROM linear_configs WHERE workspace_id = ?`, workspaceID) + err = s.ro.GetContext(ctx, &present, s.ro.Rebind( + `SELECT COUNT(*) FROM linear_configs WHERE workspace_id = ?`), workspaceID) if err != nil { return false, err } @@ -504,7 +509,7 @@ func (s *Store) HasConfigForWorkspace(ctx context.Context, workspaceID string) ( // ListConfigWorkspaceIDs returns every workspace with a saved Linear config. func (s *Store) ListConfigWorkspaceIDs(ctx context.Context) ([]string, error) { var ids []string - if err := s.ro.SelectContext(ctx, &ids, `SELECT workspace_id FROM linear_configs ORDER BY workspace_id`); err != nil { + if err := s.ro.SelectContext(ctx, &ids, s.ro.Rebind(`SELECT workspace_id FROM linear_configs ORDER BY workspace_id`)); err != nil { return nil, err } return ids, nil @@ -529,17 +534,17 @@ func (s *Store) UpdateAuthHealthForWorkspace(ctx context.Context, workspaceID st return err } if orgSlug != "" { - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` UPDATE linear_configs - SET last_checked_at = ?, last_ok = ?, last_error = ?, org_slug = ? - WHERE workspace_id = ?`, + SET last_checked_at = ?, last_ok = CASE WHEN ? THEN 1 ELSE 0 END, last_error = ?, org_slug = ? + WHERE workspace_id = ?`), checkedAt, ok, errMsg, orgSlug, workspaceID) return err } - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` UPDATE linear_configs - SET last_checked_at = ?, last_ok = ?, last_error = ? - WHERE workspace_id = ?`, + SET last_checked_at = ?, last_ok = CASE WHEN ? THEN 1 ELSE 0 END, last_error = ? + WHERE workspace_id = ?`), checkedAt, ok, errMsg, workspaceID) return err } diff --git a/apps/backend/internal/linear/store_issue_watch.go b/apps/backend/internal/linear/store_issue_watch.go index 296e13b714..aff06083bc 100644 --- a/apps/backend/internal/linear/store_issue_watch.go +++ b/apps/backend/internal/linear/store_issue_watch.go @@ -113,9 +113,9 @@ func (s *Store) CreateIssueWatch(ctx context.Context, w *IssueWatch) error { if err != nil { return err } - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO linear_issue_watches (`+issueWatchInsertColumns+`) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`), w.ID, w.WorkspaceID, w.WorkflowID, w.WorkflowStepID, w.RepositoryID, w.BaseBranch, filterJSON, w.AgentProfileID, w.ExecutorProfileID, w.Prompt, w.Enabled, @@ -138,8 +138,8 @@ func nullableInt(v *int) interface{} { // GetIssueWatch returns a single watch by ID, or nil when no row matches. func (s *Store) GetIssueWatch(ctx context.Context, id string) (*IssueWatch, error) { var row issueWatchRow - err := s.ro.GetContext(ctx, &row, - `SELECT `+issueWatchSelectColumns+` FROM linear_issue_watches WHERE id = ?`, id) + err := s.ro.GetContext(ctx, &row, s.ro.Rebind( + `SELECT `+issueWatchSelectColumns+` FROM linear_issue_watches WHERE id = ?`), id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -152,9 +152,9 @@ func (s *Store) GetIssueWatch(ctx context.Context, id string) (*IssueWatch, erro // ListIssueWatches returns all watches configured for a workspace. func (s *Store) ListIssueWatches(ctx context.Context, workspaceID string) ([]*IssueWatch, error) { var rows []issueWatchRow - err := s.ro.SelectContext(ctx, &rows, + err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( `SELECT `+issueWatchSelectColumns+` FROM linear_issue_watches - WHERE workspace_id = ? ORDER BY created_at`, workspaceID) + WHERE workspace_id = ? ORDER BY created_at`), workspaceID) if err != nil { return nil, err } @@ -164,8 +164,8 @@ func (s *Store) ListIssueWatches(ctx context.Context, workspaceID string) ([]*Is // ListAllIssueWatches returns every watch across all workspaces. func (s *Store) ListAllIssueWatches(ctx context.Context) ([]*IssueWatch, error) { var rows []issueWatchRow - err := s.ro.SelectContext(ctx, &rows, - `SELECT `+issueWatchSelectColumns+` FROM linear_issue_watches ORDER BY workspace_id, created_at`) + err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( + `SELECT `+issueWatchSelectColumns+` FROM linear_issue_watches ORDER BY workspace_id, created_at`)) if err != nil { return nil, err } @@ -176,9 +176,9 @@ func (s *Store) ListAllIssueWatches(ctx context.Context) ([]*IssueWatch, error) // used by the poller to decide what to query each tick. func (s *Store) ListEnabledIssueWatches(ctx context.Context) ([]*IssueWatch, error) { var rows []issueWatchRow - err := s.ro.SelectContext(ctx, &rows, + err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( `SELECT `+issueWatchSelectColumns+` FROM linear_issue_watches - WHERE enabled = 1 ORDER BY created_at`) + WHERE enabled = TRUE ORDER BY created_at`)) if err != nil { return nil, err } @@ -209,13 +209,13 @@ func (s *Store) UpdateIssueWatch(ctx context.Context, w *IssueWatch) error { if err != nil { return err } - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` UPDATE linear_issue_watches SET workflow_id = ?, workflow_step_id = ?, repository_id = ?, base_branch = ?, filter_json = ?, agent_profile_id = ?, executor_profile_id = ?, prompt = ?, enabled = ?, poll_interval_seconds = ?, max_inflight_tasks = ?, sort_by = ?, last_polled_at = ?, updated_at = ? - WHERE id = ?`, + WHERE id = ?`), w.WorkflowID, w.WorkflowStepID, w.RepositoryID, w.BaseBranch, filterJSON, w.AgentProfileID, w.ExecutorProfileID, w.Prompt, @@ -227,8 +227,8 @@ func (s *Store) UpdateIssueWatch(ctx context.Context, w *IssueWatch) error { // UpdateIssueWatchLastPolled stamps the last-polled timestamp without touching // the rest of the row. func (s *Store) UpdateIssueWatchLastPolled(ctx context.Context, id string, t time.Time) error { - _, err := s.db.ExecContext(ctx, - `UPDATE linear_issue_watches SET last_polled_at = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE linear_issue_watches SET last_polled_at = ?, updated_at = ? WHERE id = ?`), t, time.Now().UTC(), id) return err } @@ -240,10 +240,10 @@ func (s *Store) UpdateIssueWatchLastPolled(ctx context.Context, id string, t tim // soft-deleted (see internal/agent/runtime/lifecycle/profile_resolver.go). func (s *Store) DisableIssueWatchWithError(ctx context.Context, id, cause string) error { now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, + _, err := s.db.ExecContext(ctx, s.db.Rebind( `UPDATE linear_issue_watches - SET enabled = 0, last_error = ?, last_error_at = ?, updated_at = ? - WHERE id = ?`, + SET enabled = FALSE, last_error = ?, last_error_at = ?, updated_at = ? + WHERE id = ?`), cause, now, now, id) return err } @@ -257,10 +257,10 @@ func (s *Store) DeleteIssueWatch(ctx context.Context, id string) error { return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, `DELETE FROM linear_issue_watch_tasks WHERE issue_watch_id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind(`DELETE FROM linear_issue_watch_tasks WHERE issue_watch_id = ?`), id); err != nil { return err } - if _, err := tx.ExecContext(ctx, `DELETE FROM linear_issue_watches WHERE id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind(`DELETE FROM linear_issue_watches WHERE id = ?`), id); err != nil { return err } return tx.Commit() @@ -270,9 +270,10 @@ func (s *Store) DeleteIssueWatch(ctx context.Context, id string) error { // INSERT OR IGNORE. Returns true when this caller won the race and should // proceed to create the task. func (s *Store) ReserveIssueWatchTask(ctx context.Context, watchID, identifier, issueURL string) (bool, error) { - res, err := s.db.ExecContext(ctx, ` - INSERT OR IGNORE INTO linear_issue_watch_tasks (id, issue_watch_id, issue_identifier, issue_url, task_id, created_at) - VALUES (?, ?, ?, ?, ?, ?)`, + res, err := s.db.ExecContext(ctx, s.db.Rebind(` + INSERT INTO linear_issue_watch_tasks (id, issue_watch_id, issue_identifier, issue_url, task_id, created_at) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(issue_watch_id, issue_identifier) DO NOTHING`), uuid.New().String(), watchID, identifier, issueURL, "", time.Now().UTC()) if err != nil { return false, err @@ -287,9 +288,9 @@ func (s *Store) ReserveIssueWatchTask(ctx context.Context, watchID, identifier, // AssignIssueWatchTaskID stamps the created task ID onto a previously-reserved // dedup row. func (s *Store) AssignIssueWatchTaskID(ctx context.Context, watchID, identifier, taskID string) error { - res, err := s.db.ExecContext(ctx, ` + res, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE linear_issue_watch_tasks SET task_id = ? - WHERE issue_watch_id = ? AND issue_identifier = ?`, + WHERE issue_watch_id = ? AND issue_identifier = ?`), taskID, watchID, identifier) if err != nil { return err @@ -307,8 +308,8 @@ func (s *Store) AssignIssueWatchTaskID(ctx context.Context, watchID, identifier, // ReleaseIssueWatchTask drops a reservation so the next poll can retry. Used // when task creation fails after a successful reserve. func (s *Store) ReleaseIssueWatchTask(ctx context.Context, watchID, identifier string) error { - _, err := s.db.ExecContext(ctx, - `DELETE FROM linear_issue_watch_tasks WHERE issue_watch_id = ? AND issue_identifier = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `DELETE FROM linear_issue_watch_tasks WHERE issue_watch_id = ? AND issue_identifier = ?`), watchID, identifier) return err } @@ -317,8 +318,8 @@ func (s *Store) ReleaseIssueWatchTask(ctx context.Context, watchID, identifier s // reserved against a watch. func (s *Store) ListSeenIssueIdentifiers(ctx context.Context, watchID string) (map[string]struct{}, error) { var keys []string - err := s.ro.SelectContext(ctx, &keys, - `SELECT issue_identifier FROM linear_issue_watch_tasks WHERE issue_watch_id = ?`, watchID) + err := s.ro.SelectContext(ctx, &keys, s.ro.Rebind( + `SELECT issue_identifier FROM linear_issue_watch_tasks WHERE issue_watch_id = ?`), watchID) if err != nil { return nil, err } @@ -334,8 +335,8 @@ func (s *Store) ListSeenIssueIdentifiers(ctx context.Context, watchID string) (m // Used by the reset flow to enumerate the tasks to cascade-delete. func (s *Store) ListIssueWatchTaskIDs(ctx context.Context, watchID string) ([]string, error) { var ids []string - err := s.ro.SelectContext(ctx, &ids, - `SELECT task_id FROM linear_issue_watch_tasks WHERE issue_watch_id = ?`, watchID) + err := s.ro.SelectContext(ctx, &ids, s.ro.Rebind( + `SELECT task_id FROM linear_issue_watch_tasks WHERE issue_watch_id = ?`), watchID) return ids, err } @@ -349,12 +350,12 @@ func (s *Store) ResetIssueWatchState(ctx context.Context, watchID string) error return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, - `DELETE FROM linear_issue_watch_tasks WHERE issue_watch_id = ?`, watchID); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind( + `DELETE FROM linear_issue_watch_tasks WHERE issue_watch_id = ?`), watchID); err != nil { return err } - if _, err := tx.ExecContext(ctx, - `UPDATE linear_issue_watches SET last_polled_at = NULL, updated_at = ? WHERE id = ?`, + if _, err := tx.ExecContext(ctx, s.db.Rebind( + `UPDATE linear_issue_watches SET last_polled_at = NULL, updated_at = ? WHERE id = ?`), time.Now().UTC(), watchID); err != nil { return err } diff --git a/apps/backend/internal/linear/store_postgres_test.go b/apps/backend/internal/linear/store_postgres_test.go new file mode 100644 index 0000000000..25e5b7b7d2 --- /dev/null +++ b/apps/backend/internal/linear/store_postgres_test.go @@ -0,0 +1,71 @@ +package linear + +import ( + "context" + "testing" + "time" + + "github.com/kandev/kandev/internal/testutil" +) + +func TestPostgresStoreSchemaReplay(t *testing.T) { + ctx := context.Background() + database := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t)) + + store, err := NewStore(database, database) + if err != nil { + t.Fatalf("first Linear store schema init: %v", err) + } + if _, err := NewStore(database, database); err != nil { + t.Fatalf("second Linear store schema init: %v", err) + } + + config := &LinearConfig{AuthMethod: AuthMethodAPIKey, DefaultTeamKey: "ENG"} + if err := store.UpsertConfigForWorkspace(ctx, "ws-1", config); err != nil { + t.Fatalf("upsert Linear config: %v", err) + } + gotConfig, err := store.GetConfigForWorkspace(ctx, "ws-1") + if err != nil || gotConfig == nil || gotConfig.DefaultTeamKey != config.DefaultTeamKey { + t.Fatalf("get Linear config: config=%+v err=%v", gotConfig, err) + } + if err := store.UpdateAuthHealthForWorkspace(ctx, "ws-1", true, "", "acme", time.Now().UTC()); err != nil { + t.Fatalf("update Linear auth health: %v", err) + } + + watch := &IssueWatch{ + WorkspaceID: "ws-1", + WorkflowID: "workflow-1", + WorkflowStepID: "step-1", + Filter: SearchFilter{Query: "priority:high"}, + AgentProfileID: "agent-1", + ExecutorProfileID: "executor-1", + Enabled: true, + SortBy: SortByPriorityDesc, + } + if err := store.CreateIssueWatch(ctx, watch); err != nil { + t.Fatalf("create Linear issue watch: %v", err) + } + gotWatch, err := store.GetIssueWatch(ctx, watch.ID) + if err != nil || gotWatch == nil || gotWatch.Filter.Query != watch.Filter.Query { + t.Fatalf("get Linear issue watch: watch=%+v err=%v", gotWatch, err) + } + if enabled, err := store.ListEnabledIssueWatches(ctx); err != nil || len(enabled) != 1 { + t.Fatalf("list enabled Linear issue watches: watches=%d err=%v", len(enabled), err) + } + + reserved, err := store.ReserveIssueWatchTask(ctx, watch.ID, "ENG-123", "https://linear.app/acme/issue/ENG-123") + if err != nil || !reserved { + t.Fatalf("reserve Linear issue: reserved=%v err=%v", reserved, err) + } + reserved, err = store.ReserveIssueWatchTask(ctx, watch.ID, "ENG-123", "https://linear.app/acme/issue/ENG-123") + if err != nil || reserved { + t.Fatalf("duplicate Linear issue reservation: reserved=%v err=%v", reserved, err) + } + if err := store.AssignIssueWatchTaskID(ctx, watch.ID, "ENG-123", "task-1"); err != nil { + t.Fatalf("assign Linear issue task: %v", err) + } + seen, err := store.ListSeenIssueIdentifiers(ctx, watch.ID) + if err != nil || len(seen) != 1 { + t.Fatalf("list Linear seen issues: seen=%d err=%v", len(seen), err) + } +} diff --git a/apps/backend/internal/sentry/store.go b/apps/backend/internal/sentry/store.go index 87d9a9c550..26e84c7fc2 100644 --- a/apps/backend/internal/sentry/store.go +++ b/apps/backend/internal/sentry/store.go @@ -10,8 +10,11 @@ import ( "time" "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgconn" "github.com/jmoiron/sqlx" + dbutil "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/db/dialect" "github.com/kandev/kandev/internal/integrations/workspacescope" ) @@ -134,7 +137,7 @@ func (s *Store) initSchema() error { if err := s.migrateConfigsTableToInstances(); err != nil { return err } - if _, err := s.db.Exec(createTablesSQL); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(createTablesSQL, s.db.DriverName())); err != nil { return err } if err := s.addConfigURLColumn(); err != nil { @@ -162,6 +165,9 @@ func (s *Store) initSchema() error { } func (s *Store) migrateLegacySingletonTable() error { + if dialect.IsPostgres(s.db.DriverName()) { + return nil + } cols, err := s.tableColumns("sentry_configs") if err != nil { return err @@ -258,6 +264,9 @@ type legacyWorkspaceConfig struct { // has an id column (fresh install or a completed prior run) is left untouched, // so a crash between this step and the watch rebuild re-runs safely. func (s *Store) migrateConfigsTableToInstances() error { + if dialect.IsPostgres(s.db.DriverName()) { + return nil + } cols, err := s.tableColumns("sentry_configs") if err != nil { return err @@ -356,6 +365,9 @@ func (s *Store) readLegacyWorkspaceConfigs(cols map[string]struct{}) ([]legacyWo // already has the exact nullable-FK target shape, so a crash mid-migration (or // an older wrong-shaped column) always re-runs safely. func (s *Store) migrateWatchesAddInstanceColumn() error { + if dialect.IsPostgres(s.db.DriverName()) { + return nil + } cols, err := s.tableColumns("sentry_issue_watches") if err != nil { return err @@ -670,12 +682,12 @@ func (s *Store) addIssueWatchRepositoryColumns() error { return nil } if _, ok := cols["repository_id"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE sentry_issue_watches ADD COLUMN repository_id TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE sentry_issue_watches ADD COLUMN repository_id TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add repository_id column: %w", err) } } if _, ok := cols["base_branch"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE sentry_issue_watches ADD COLUMN base_branch TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE sentry_issue_watches ADD COLUMN base_branch TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add base_branch column: %w", err) } } @@ -696,7 +708,7 @@ func (s *Store) addConfigURLColumn() error { if _, ok := cols["url"]; ok { return nil } - if _, err := s.db.Exec(`ALTER TABLE sentry_configs ADD COLUMN url TEXT NOT NULL DEFAULT 'https://sentry.io'`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE sentry_configs ADD COLUMN url TEXT NOT NULL DEFAULT 'https://sentry.io'`, s.db.DriverName())); err != nil { return fmt.Errorf("add url column: %w", err) } return nil @@ -716,7 +728,7 @@ func (s *Store) addMaxInflightTasksColumn() error { if _, ok := cols["max_inflight_tasks"]; ok { return nil } - if _, err := s.db.Exec(`ALTER TABLE sentry_issue_watches ADD COLUMN max_inflight_tasks INTEGER DEFAULT 5`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE sentry_issue_watches ADD COLUMN max_inflight_tasks INTEGER DEFAULT 5`, s.db.DriverName())); err != nil { return fmt.Errorf("add max_inflight_tasks column: %w", err) } return nil @@ -734,12 +746,12 @@ func (s *Store) addIssueWatchLastErrorColumns() error { return nil } if _, ok := cols["last_error"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE sentry_issue_watches ADD COLUMN last_error TEXT NOT NULL DEFAULT ''`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE sentry_issue_watches ADD COLUMN last_error TEXT NOT NULL DEFAULT ''`, s.db.DriverName())); err != nil { return fmt.Errorf("add last_error column: %w", err) } } if _, ok := cols["last_error_at"]; !ok { - if _, err := s.db.Exec(`ALTER TABLE sentry_issue_watches ADD COLUMN last_error_at DATETIME`); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(`ALTER TABLE sentry_issue_watches ADD COLUMN last_error_at DATETIME`, s.db.DriverName())); err != nil { return fmt.Errorf("add last_error_at column: %w", err) } } @@ -750,27 +762,27 @@ func (s *Store) addIssueWatchLastErrorColumns() error { // table_info, used by the lightweight ADD COLUMN migrations and the shape // detection guarding the table rebuilds above. func (s *Store) tableColumns(table string) (map[string]struct{}, error) { - rows, err := s.db.Query(fmt.Sprintf("PRAGMA table_info(%s)", table)) + columns, err := dbutil.TableColumns(s.db, table) if err != nil { return nil, err } - defer func() { _ = rows.Close() }() - cols := make(map[string]struct{}) - for rows.Next() { - var ( - cid int - name string - ctype string - notnull int - dflt sql.NullString - pk int - ) - if err := rows.Scan(&cid, &name, &ctype, ¬null, &dflt, &pk); err != nil { - return nil, err - } + cols := make(map[string]struct{}, len(columns)) + for name := range columns { cols[name] = struct{}{} } - return cols, rows.Err() + return cols, nil +} + +func schemaSQLForDriver(schema, driver string) string { + schema = strings.ReplaceAll(schema, "TIMESTAMP", dialect.TimestampType(driver)) + schema = strings.ReplaceAll(schema, "DATETIME", dialect.TimestampType(driver)) + if dialect.IsPostgres(driver) { + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 1", "BOOLEAN NOT NULL DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN NOT NULL DEFAULT 0", "BOOLEAN NOT NULL DEFAULT FALSE") + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 1", "BOOLEAN DEFAULT TRUE") + schema = strings.ReplaceAll(schema, "BOOLEAN DEFAULT 0", "BOOLEAN DEFAULT FALSE") + } + return schema } const selectInstanceColumns = `id, workspace_id, name, auth_method, url, @@ -779,8 +791,8 @@ const selectInstanceColumns = `id, workspace_id, name, auth_method, url, // ListInstances returns every Sentry instance in a workspace, ordered by name. func (s *Store) ListInstances(ctx context.Context, workspaceID string) ([]*SentryConfig, error) { var rows []SentryConfig - if err := s.ro.SelectContext(ctx, &rows, - `SELECT `+selectInstanceColumns+` FROM sentry_configs WHERE workspace_id = ? ORDER BY name, id`, + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( + `SELECT `+selectInstanceColumns+` FROM sentry_configs WHERE workspace_id = ? ORDER BY name, id`), workspaceID); err != nil { return nil, err } @@ -791,8 +803,8 @@ func (s *Store) ListInstances(ctx context.Context, workspaceID string) ([]*Sentr // auth-health poller and the provider secret rekey. func (s *Store) ListAllInstances(ctx context.Context) ([]*SentryConfig, error) { var rows []SentryConfig - if err := s.ro.SelectContext(ctx, &rows, - `SELECT `+selectInstanceColumns+` FROM sentry_configs ORDER BY workspace_id, name, id`); err != nil { + if err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( + `SELECT `+selectInstanceColumns+` FROM sentry_configs ORDER BY workspace_id, name, id`)); err != nil { return nil, err } return instancePtrs(rows), nil @@ -802,8 +814,8 @@ func (s *Store) ListAllInstances(ctx context.Context) ([]*SentryConfig, error) { // is checked by the service against the request's workspace. func (s *Store) GetInstance(ctx context.Context, id string) (*SentryConfig, error) { var cfg SentryConfig - err := s.ro.GetContext(ctx, &cfg, - `SELECT `+selectInstanceColumns+` FROM sentry_configs WHERE id = ?`, id) + err := s.ro.GetContext(ctx, &cfg, s.ro.Rebind( + `SELECT `+selectInstanceColumns+` FROM sentry_configs WHERE id = ?`), id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -825,9 +837,9 @@ func (s *Store) CreateInstance(ctx context.Context, cfg *SentryConfig) error { cfg.CreatedAt = now } cfg.UpdatedAt = now - _, err := s.db.ExecContext(ctx, ` + _, err := s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO sentry_configs (id, workspace_id, name, auth_method, url, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?)`), cfg.ID, cfg.WorkspaceID, cfg.Name, cfg.AuthMethod, cfg.URL, cfg.CreatedAt, cfg.UpdatedAt) if isUniqueViolation(err) { return ErrDuplicateInstanceName @@ -840,9 +852,9 @@ func (s *Store) CreateInstance(ctx context.Context, cfg *SentryConfig) error { // when no row matches and ErrDuplicateInstanceName on a name collision. func (s *Store) UpdateInstance(ctx context.Context, cfg *SentryConfig) error { cfg.UpdatedAt = time.Now().UTC() - res, err := s.db.ExecContext(ctx, ` + res, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE sentry_configs SET name = ?, auth_method = ?, url = ?, updated_at = ? - WHERE id = ?`, + WHERE id = ?`), cfg.Name, cfg.AuthMethod, cfg.URL, cfg.UpdatedAt, cfg.ID) if isUniqueViolation(err) { return ErrDuplicateInstanceName @@ -864,7 +876,7 @@ func (s *Store) UpdateInstance(ctx context.Context, cfg *SentryConfig) error { // the ON DELETE RESTRICT foreign key, surfaced as ErrInstanceInUse (the service // fills the watch count). Returns ErrInstanceNotFound when no row matches. func (s *Store) DeleteInstance(ctx context.Context, id string) error { - res, err := s.db.ExecContext(ctx, `DELETE FROM sentry_configs WHERE id = ?`, id) + res, err := s.db.ExecContext(ctx, s.db.Rebind(`DELETE FROM sentry_configs WHERE id = ?`), id) if isForeignKeyViolation(err) { return ErrInstanceInUse{} } @@ -885,8 +897,8 @@ func (s *Store) DeleteInstance(ctx context.Context, id string) error { // instance, used to reject deletion of an in-use instance with a friendly count. func (s *Store) CountWatchesForInstance(ctx context.Context, instanceID string) (int, error) { var n int - if err := s.ro.GetContext(ctx, &n, - `SELECT COUNT(*) FROM sentry_issue_watches WHERE sentry_instance_id = ?`, instanceID); err != nil { + if err := s.ro.GetContext(ctx, &n, s.ro.Rebind( + `SELECT COUNT(*) FROM sentry_issue_watches WHERE sentry_instance_id = ?`), instanceID); err != nil { return 0, err } return n, nil @@ -898,8 +910,8 @@ func (s *Store) CountWatchesForInstance(ctx context.Context, instanceID string) // poll time, so deleting that sole instance would strand them. func (s *Store) CountUnboundIssueWatchesInWorkspace(ctx context.Context, workspaceID string) (int, error) { var n int - if err := s.ro.GetContext(ctx, &n, - `SELECT COUNT(*) FROM sentry_issue_watches WHERE workspace_id = ? AND sentry_instance_id IS NULL`, workspaceID); err != nil { + if err := s.ro.GetContext(ctx, &n, s.ro.Rebind( + `SELECT COUNT(*) FROM sentry_issue_watches WHERE workspace_id = ? AND sentry_instance_id IS NULL`), workspaceID); err != nil { return 0, err } return n, nil @@ -908,10 +920,10 @@ func (s *Store) CountUnboundIssueWatchesInWorkspace(ctx context.Context, workspa // UpdateAuthHealthForInstance records the result of a credential probe on one // instance row. func (s *Store) UpdateAuthHealthForInstance(ctx context.Context, id string, ok bool, errMsg string, checkedAt time.Time) error { - res, err := s.db.ExecContext(ctx, ` + res, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE sentry_configs - SET last_checked_at = ?, last_ok = ?, last_error = ? - WHERE id = ?`, + SET last_checked_at = ?, last_ok = CASE WHEN ? THEN 1 ELSE 0 END, last_error = ? + WHERE id = ?`), checkedAt, ok, errMsg, id) if err != nil { return err @@ -930,7 +942,7 @@ func (s *Store) UpdateAuthHealthForInstance(ctx context.Context, id string, ok b // to decide whether to probe at all. func (s *Store) HasConfig(ctx context.Context) (bool, error) { var present int - if err := s.ro.GetContext(ctx, &present, `SELECT COUNT(*) FROM sentry_configs`); err != nil { + if err := s.ro.GetContext(ctx, &present, s.ro.Rebind(`SELECT COUNT(*) FROM sentry_configs`)); err != nil { return false, err } return present > 0, nil @@ -945,9 +957,16 @@ func instancePtrs(rows []SentryConfig) []*SentryConfig { } func isUniqueViolation(err error) bool { - return err != nil && strings.Contains(err.Error(), "UNIQUE constraint failed") + if err == nil { + return false + } + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + return pgErr.Code == "23505" + } + return strings.Contains(err.Error(), "UNIQUE constraint failed") } func isForeignKeyViolation(err error) bool { - return err != nil && strings.Contains(err.Error(), "FOREIGN KEY constraint failed") + return dbutil.IsForeignKeyViolation(err) } diff --git a/apps/backend/internal/sentry/store_issue_watch.go b/apps/backend/internal/sentry/store_issue_watch.go index 74afd648ed..28f9489eeb 100644 --- a/apps/backend/internal/sentry/store_issue_watch.go +++ b/apps/backend/internal/sentry/store_issue_watch.go @@ -133,9 +133,9 @@ func (s *Store) CreateIssueWatch(ctx context.Context, w *IssueWatch) error { if err != nil { return err } - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` INSERT INTO sentry_issue_watches (`+issueWatchInsertColumns+`) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`), w.ID, w.WorkspaceID, nullableString(w.SentryInstanceID), w.WorkflowID, w.WorkflowStepID, w.RepositoryID, w.BaseBranch, filterJSON, w.AgentProfileID, w.ExecutorProfileID, w.Prompt, w.Enabled, @@ -148,8 +148,8 @@ func (s *Store) CreateIssueWatch(ctx context.Context, w *IssueWatch) error { // GetIssueWatch returns a single watch by ID, or nil when no row matches. func (s *Store) GetIssueWatch(ctx context.Context, id string) (*IssueWatch, error) { var row issueWatchRow - err := s.ro.GetContext(ctx, &row, - `SELECT `+issueWatchSelectColumns+` FROM sentry_issue_watches WHERE id = ?`, id) + err := s.ro.GetContext(ctx, &row, s.ro.Rebind( + `SELECT `+issueWatchSelectColumns+` FROM sentry_issue_watches WHERE id = ?`), id) if errors.Is(err, sql.ErrNoRows) { return nil, nil } @@ -162,9 +162,9 @@ func (s *Store) GetIssueWatch(ctx context.Context, id string) (*IssueWatch, erro // ListIssueWatches returns all watches configured for a workspace. func (s *Store) ListIssueWatches(ctx context.Context, workspaceID string) ([]*IssueWatch, error) { var rows []issueWatchRow - err := s.ro.SelectContext(ctx, &rows, + err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( `SELECT `+issueWatchSelectColumns+` FROM sentry_issue_watches - WHERE workspace_id = ? ORDER BY created_at`, workspaceID) + WHERE workspace_id = ? ORDER BY created_at`), workspaceID) if err != nil { return nil, err } @@ -174,8 +174,8 @@ func (s *Store) ListIssueWatches(ctx context.Context, workspaceID string) ([]*Is // ListAllIssueWatches returns every watch across all workspaces. func (s *Store) ListAllIssueWatches(ctx context.Context) ([]*IssueWatch, error) { var rows []issueWatchRow - err := s.ro.SelectContext(ctx, &rows, - `SELECT `+issueWatchSelectColumns+` FROM sentry_issue_watches ORDER BY workspace_id, created_at`) + err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( + `SELECT `+issueWatchSelectColumns+` FROM sentry_issue_watches ORDER BY workspace_id, created_at`)) if err != nil { return nil, err } @@ -186,9 +186,9 @@ func (s *Store) ListAllIssueWatches(ctx context.Context) ([]*IssueWatch, error) // used by the poller to decide what to query each tick. func (s *Store) ListEnabledIssueWatches(ctx context.Context) ([]*IssueWatch, error) { var rows []issueWatchRow - err := s.ro.SelectContext(ctx, &rows, + err := s.ro.SelectContext(ctx, &rows, s.ro.Rebind( `SELECT `+issueWatchSelectColumns+` FROM sentry_issue_watches - WHERE enabled = 1 ORDER BY created_at`) + WHERE enabled = TRUE ORDER BY created_at`)) if err != nil { return nil, err } @@ -221,12 +221,12 @@ func (s *Store) UpdateIssueWatch(ctx context.Context, w *IssueWatch) error { if err != nil { return err } - _, err = s.db.ExecContext(ctx, ` + _, err = s.db.ExecContext(ctx, s.db.Rebind(` UPDATE sentry_issue_watches SET workflow_id = ?, workflow_step_id = ?, repository_id = ?, base_branch = ?, filter_json = ?, agent_profile_id = ?, executor_profile_id = ?, prompt = ?, enabled = ?, poll_interval_seconds = ?, max_inflight_tasks = ?, updated_at = ? - WHERE id = ?`, + WHERE id = ?`), w.WorkflowID, w.WorkflowStepID, w.RepositoryID, w.BaseBranch, filterJSON, w.AgentProfileID, w.ExecutorProfileID, w.Prompt, @@ -237,8 +237,8 @@ func (s *Store) UpdateIssueWatch(ctx context.Context, w *IssueWatch) error { // UpdateIssueWatchLastPolled stamps the last-polled timestamp without touching // the rest of the row. func (s *Store) UpdateIssueWatchLastPolled(ctx context.Context, id string, t time.Time) error { - _, err := s.db.ExecContext(ctx, - `UPDATE sentry_issue_watches SET last_polled_at = ?, updated_at = ? WHERE id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `UPDATE sentry_issue_watches SET last_polled_at = ?, updated_at = ? WHERE id = ?`), t, time.Now().UTC(), id) return err } @@ -249,10 +249,10 @@ func (s *Store) UpdateIssueWatchLastPolled(ctx context.Context, id string, t tim // UI can explain why the watch stopped firing. Mirrors the Linear/Jira stores. func (s *Store) DisableIssueWatchWithError(ctx context.Context, id, cause string) error { now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, + _, err := s.db.ExecContext(ctx, s.db.Rebind( `UPDATE sentry_issue_watches - SET enabled = 0, last_error = ?, last_error_at = ?, updated_at = ? - WHERE id = ?`, + SET enabled = FALSE, last_error = ?, last_error_at = ?, updated_at = ? + WHERE id = ?`), cause, now, now, id) return err } @@ -263,10 +263,10 @@ func (s *Store) DisableIssueWatchWithError(ctx context.Context, id, cause string // retrying. Used when an unbound watch cannot resolve a Sentry instance. func (s *Store) StampIssueWatchError(ctx context.Context, id, cause string) error { now := time.Now().UTC() - _, err := s.db.ExecContext(ctx, + _, err := s.db.ExecContext(ctx, s.db.Rebind( `UPDATE sentry_issue_watches SET last_error = ?, last_error_at = ?, updated_at = ? - WHERE id = ?`, + WHERE id = ?`), cause, now, now, id) return err } @@ -274,10 +274,10 @@ func (s *Store) StampIssueWatchError(ctx context.Context, id, cause string) erro // ClearIssueWatchError removes the non-fatal poll error state after a // successful watch check so the settings UI reflects current health. func (s *Store) ClearIssueWatchError(ctx context.Context, id string) error { - _, err := s.db.ExecContext(ctx, + _, err := s.db.ExecContext(ctx, s.db.Rebind( `UPDATE sentry_issue_watches SET last_error = '', last_error_at = NULL, updated_at = ? - WHERE id = ? AND (last_error <> '' OR last_error_at IS NOT NULL)`, + WHERE id = ? AND (last_error <> '' OR last_error_at IS NOT NULL)`), time.Now().UTC(), id) return err } @@ -291,10 +291,10 @@ func (s *Store) DeleteIssueWatch(ctx context.Context, id string) error { return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, `DELETE FROM sentry_issue_watch_tasks WHERE issue_watch_id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind(`DELETE FROM sentry_issue_watch_tasks WHERE issue_watch_id = ?`), id); err != nil { return err } - if _, err := tx.ExecContext(ctx, `DELETE FROM sentry_issue_watches WHERE id = ?`, id); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind(`DELETE FROM sentry_issue_watches WHERE id = ?`), id); err != nil { return err } return tx.Commit() @@ -304,9 +304,10 @@ func (s *Store) DeleteIssueWatch(ctx context.Context, id string) error { // INSERT OR IGNORE. Returns true when this caller won the race and should // proceed to create the task. func (s *Store) ReserveIssueWatchTask(ctx context.Context, watchID, shortID, issueURL string) (bool, error) { - res, err := s.db.ExecContext(ctx, ` - INSERT OR IGNORE INTO sentry_issue_watch_tasks (id, issue_watch_id, issue_short_id, issue_url, task_id, created_at) - VALUES (?, ?, ?, ?, ?, ?)`, + res, err := s.db.ExecContext(ctx, s.db.Rebind(` + INSERT INTO sentry_issue_watch_tasks (id, issue_watch_id, issue_short_id, issue_url, task_id, created_at) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(issue_watch_id, issue_short_id) DO NOTHING`), uuid.New().String(), watchID, shortID, issueURL, "", time.Now().UTC()) if err != nil { return false, err @@ -321,9 +322,9 @@ func (s *Store) ReserveIssueWatchTask(ctx context.Context, watchID, shortID, iss // AssignIssueWatchTaskID stamps the created task ID onto a previously-reserved // dedup row. func (s *Store) AssignIssueWatchTaskID(ctx context.Context, watchID, shortID, taskID string) error { - res, err := s.db.ExecContext(ctx, ` + res, err := s.db.ExecContext(ctx, s.db.Rebind(` UPDATE sentry_issue_watch_tasks SET task_id = ? - WHERE issue_watch_id = ? AND issue_short_id = ?`, + WHERE issue_watch_id = ? AND issue_short_id = ?`), taskID, watchID, shortID) if err != nil { return err @@ -341,8 +342,8 @@ func (s *Store) AssignIssueWatchTaskID(ctx context.Context, watchID, shortID, ta // ReleaseIssueWatchTask drops a reservation so the next poll can retry. Used // when task creation fails after a successful reserve. func (s *Store) ReleaseIssueWatchTask(ctx context.Context, watchID, shortID string) error { - _, err := s.db.ExecContext(ctx, - `DELETE FROM sentry_issue_watch_tasks WHERE issue_watch_id = ? AND issue_short_id = ?`, + _, err := s.db.ExecContext(ctx, s.db.Rebind( + `DELETE FROM sentry_issue_watch_tasks WHERE issue_watch_id = ? AND issue_short_id = ?`), watchID, shortID) return err } @@ -351,8 +352,8 @@ func (s *Store) ReleaseIssueWatchTask(ctx context.Context, watchID, shortID stri // against a watch. func (s *Store) ListSeenIssueShortIDs(ctx context.Context, watchID string) (map[string]struct{}, error) { var keys []string - err := s.ro.SelectContext(ctx, &keys, - `SELECT issue_short_id FROM sentry_issue_watch_tasks WHERE issue_watch_id = ?`, watchID) + err := s.ro.SelectContext(ctx, &keys, s.ro.Rebind( + `SELECT issue_short_id FROM sentry_issue_watch_tasks WHERE issue_watch_id = ?`), watchID) if err != nil { return nil, err } @@ -368,8 +369,8 @@ func (s *Store) ListSeenIssueShortIDs(ctx context.Context, watchID string) (map[ // Used by the reset flow to enumerate the tasks to cascade-delete. func (s *Store) ListIssueWatchTaskIDs(ctx context.Context, watchID string) ([]string, error) { var ids []string - err := s.ro.SelectContext(ctx, &ids, - `SELECT task_id FROM sentry_issue_watch_tasks WHERE issue_watch_id = ?`, watchID) + err := s.ro.SelectContext(ctx, &ids, s.ro.Rebind( + `SELECT task_id FROM sentry_issue_watch_tasks WHERE issue_watch_id = ?`), watchID) return ids, err } @@ -383,12 +384,12 @@ func (s *Store) ResetIssueWatchState(ctx context.Context, watchID string) error return err } defer func() { _ = tx.Rollback() }() - if _, err := tx.ExecContext(ctx, - `DELETE FROM sentry_issue_watch_tasks WHERE issue_watch_id = ?`, watchID); err != nil { + if _, err := tx.ExecContext(ctx, s.db.Rebind( + `DELETE FROM sentry_issue_watch_tasks WHERE issue_watch_id = ?`), watchID); err != nil { return err } - if _, err := tx.ExecContext(ctx, - `UPDATE sentry_issue_watches SET last_polled_at = NULL, updated_at = ? WHERE id = ?`, + if _, err := tx.ExecContext(ctx, s.db.Rebind( + `UPDATE sentry_issue_watches SET last_polled_at = NULL, updated_at = ? WHERE id = ?`), time.Now().UTC(), watchID); err != nil { return err } diff --git a/apps/backend/internal/sentry/store_postgres_test.go b/apps/backend/internal/sentry/store_postgres_test.go new file mode 100644 index 0000000000..6cd8d32a67 --- /dev/null +++ b/apps/backend/internal/sentry/store_postgres_test.go @@ -0,0 +1,83 @@ +package sentry + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/kandev/kandev/internal/testutil" +) + +func TestPostgresStoreSchemaReplay(t *testing.T) { + ctx := context.Background() + database := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t)) + + store, err := NewStore(database, database) + if err != nil { + t.Fatalf("first Sentry store schema init: %v", err) + } + if _, err := NewStore(database, database); err != nil { + t.Fatalf("second Sentry store schema init: %v", err) + } + + instance := &SentryConfig{ + WorkspaceID: "ws-1", + Name: "SaaS", + AuthMethod: AuthMethodAuthToken, + URL: "https://sentry.io", + } + if err := store.CreateInstance(ctx, instance); err != nil { + t.Fatalf("create Sentry instance: %v", err) + } + gotInstance, err := store.GetInstance(ctx, instance.ID) + if err != nil || gotInstance == nil || gotInstance.Name != instance.Name { + t.Fatalf("get Sentry instance: instance=%+v err=%v", gotInstance, err) + } + if err := store.UpdateAuthHealthForInstance(ctx, instance.ID, true, "", time.Now().UTC()); err != nil { + t.Fatalf("update Sentry auth health: %v", err) + } + + watch := &IssueWatch{ + WorkspaceID: "ws-1", + SentryInstanceID: instance.ID, + WorkflowID: "workflow-1", + WorkflowStepID: "step-1", + Filter: SearchFilter{Query: "is:unresolved"}, + AgentProfileID: "agent-1", + ExecutorProfileID: "executor-1", + Enabled: true, + } + if err := store.CreateIssueWatch(ctx, watch); err != nil { + t.Fatalf("create Sentry issue watch: %v", err) + } + gotWatch, err := store.GetIssueWatch(ctx, watch.ID) + if err != nil || gotWatch == nil || gotWatch.SentryInstanceID != instance.ID { + t.Fatalf("get Sentry issue watch: watch=%+v err=%v", gotWatch, err) + } + if enabled, err := store.ListEnabledIssueWatches(ctx); err != nil || len(enabled) != 1 { + t.Fatalf("list enabled Sentry issue watches: watches=%d err=%v", len(enabled), err) + } + if count, err := store.CountWatchesForInstance(ctx, instance.ID); err != nil || count != 1 { + t.Fatalf("count Sentry instance watches: count=%d err=%v", count, err) + } + + reserved, err := store.ReserveIssueWatchTask(ctx, watch.ID, "PROJ-123", "https://sentry.io/issues/PROJ-123") + if err != nil || !reserved { + t.Fatalf("reserve Sentry issue: reserved=%v err=%v", reserved, err) + } + reserved, err = store.ReserveIssueWatchTask(ctx, watch.ID, "PROJ-123", "https://sentry.io/issues/PROJ-123") + if err != nil || reserved { + t.Fatalf("duplicate Sentry issue reservation: reserved=%v err=%v", reserved, err) + } + if err := store.AssignIssueWatchTaskID(ctx, watch.ID, "PROJ-123", "task-1"); err != nil { + t.Fatalf("assign Sentry issue task: %v", err) + } + seen, err := store.ListSeenIssueShortIDs(ctx, watch.ID) + if err != nil || len(seen) != 1 { + t.Fatalf("list Sentry seen issues: seen=%d err=%v", len(seen), err) + } + if err := store.DeleteInstance(ctx, instance.ID); !errors.As(err, &ErrInstanceInUse{}) { + t.Fatalf("expected Sentry instance FK protection, got %v", err) + } +} diff --git a/apps/backend/internal/workflowsync/store.go b/apps/backend/internal/workflowsync/store.go index 6ad63e59cf..679d079c87 100644 --- a/apps/backend/internal/workflowsync/store.go +++ b/apps/backend/internal/workflowsync/store.go @@ -6,11 +6,13 @@ import ( "encoding/json" "errors" "fmt" + "strings" "time" "github.com/jmoiron/sqlx" "github.com/kandev/kandev/internal/db" + "github.com/kandev/kandev/internal/db/dialect" ) // Store persists workspace-scoped workflow sync configuration. @@ -50,7 +52,7 @@ const createTablesSQL = ` ` func (s *Store) initSchema() error { - if _, err := s.db.Exec(createTablesSQL); err != nil { + if _, err := s.db.Exec(schemaSQLForDriver(createTablesSQL, s.db.DriverName())); err != nil { return err } if err := s.addPollEnabledColumn(); err != nil { @@ -156,7 +158,7 @@ func (s *Store) GetConfigForWorkspace(ctx context.Context, workspaceID string) ( // ListConfigs returns every stored config, for the background poller. func (s *Store) ListConfigs(ctx context.Context) ([]*Config, error) { - rows, err := s.ro.QueryContext(ctx, `SELECT `+configSelectColumns+` FROM workflow_sync_configs ORDER BY workspace_id`) + rows, err := s.ro.QueryContext(ctx, s.ro.Rebind(`SELECT `+configSelectColumns+` FROM workflow_sync_configs ORDER BY workspace_id`)) if err != nil { return nil, err } @@ -237,3 +239,7 @@ func boolToInt(b bool) int { } return 0 } + +func schemaSQLForDriver(schema, driver string) string { + return strings.ReplaceAll(schema, "DATETIME", dialect.TimestampType(driver)) +} diff --git a/apps/backend/internal/workflowsync/store_postgres_test.go b/apps/backend/internal/workflowsync/store_postgres_test.go new file mode 100644 index 0000000000..73e50c1157 --- /dev/null +++ b/apps/backend/internal/workflowsync/store_postgres_test.go @@ -0,0 +1,58 @@ +package workflowsync + +import ( + "context" + "testing" + "time" + + "github.com/kandev/kandev/internal/testutil" +) + +func TestPostgresStoreSchemaReplay(t *testing.T) { + ctx := context.Background() + database := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t)) + + store, err := NewStore(database, database) + if err != nil { + t.Fatalf("first workflow sync store schema init: %v", err) + } + replayed, err := NewStore(database, database) + if err != nil { + t.Fatalf("second workflow sync store schema init: %v", err) + } + + pollEnabled := true + request := &SetConfigRequest{ + Provider: ProviderGitHub, + RepoOwner: "acme", + RepoName: "workflows", + Branch: "main", + Path: ".github/workflows", + IntervalSeconds: 120, + PollEnabled: &pollEnabled, + } + if err := request.Normalize(); err != nil { + t.Fatalf("normalize workflow sync config: %v", err) + } + if _, err := replayed.UpsertConfigForWorkspace(ctx, "ws-1", request); err != nil { + t.Fatalf("upsert workflow sync config: %v", err) + } + updatedAt := time.Now().UTC().Truncate(time.Microsecond) + if err := replayed.RecordSyncStatus(ctx, "ws-1", true, "", []string{"warning"}, "hash-1", updatedAt); err != nil { + t.Fatalf("record workflow sync status: %v", err) + } + config, err := replayed.GetConfigForWorkspace(ctx, "ws-1") + if err != nil || config == nil || !config.LastOk || !config.PollEnabled || config.LastHash != "hash-1" { + t.Fatalf("workflow sync config = %+v, err=%v", config, err) + } + configs, err := replayed.ListConfigs(ctx) + if err != nil || len(configs) != 1 || configs[0].WorkspaceID != "ws-1" { + t.Fatalf("workflow sync configs = %+v, err=%v", configs, err) + } + if err := replayed.DeleteConfigForWorkspace(ctx, "ws-1"); err != nil { + t.Fatalf("delete workflow sync config: %v", err) + } + if config, err := store.GetConfigForWorkspace(ctx, "ws-1"); err != nil || config != nil { + t.Fatalf("workflow sync config after delete = %+v, err=%v", config, err) + } +} diff --git a/docs/plans/postgres-domain-store-parity/plan.md b/docs/plans/postgres-domain-store-parity/plan.md new file mode 100644 index 0000000000..ce1d0bfba5 --- /dev/null +++ b/docs/plans/postgres-domain-store-parity/plan.md @@ -0,0 +1,125 @@ +--- +created: 2026-09-03 +status: done +requirements: + - REQ-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001 +system_design: + - ../../specs/platform/system-design/postgres-domain-store-parity.md +legacy_specs: [] +--- + +# Implementation Plan: PostgreSQL Domain Store Parity + +## Overview + +This work restores PostgreSQL support for eight built-in domain stores. Shared dialect helpers land first, followed by focused provider conversions and a boot regression. + +The order keeps each store reviewable. Each store gets real PostgreSQL schema replay and operation coverage before the final boot test changes. + +## Scope + +### In scope + +- Make schema types and schema introspection portable. +- Rebind all affected store queries before execution. +- Replace SQLite-only conflict and boolean syntax in shared paths. +- Add PostgreSQL tests for schema replay and representative store operations. +- Make the PostgreSQL boot test detect unavailable integration and automation stores. + +### Out of scope + +- Provider API behavior and authentication changes. +- Active-active PostgreSQL support. +- A new migration framework. +- Frontend behavior changes. + +## Confirmed root cause + +The eight stores use SQLite schema types, catalog queries, conflict syntax, or unresolved `?` placeholders. PostgreSQL rejects these statements. + +Provider construction errors are nonfatal. Therefore, the existing boot test returns success while services or stores remain unavailable. + +## Technical approach + +### Shared database helpers + +Add portable timestamp and schema-introspection helpers under `internal/db`. Reuse the active `sqlx` driver name and current PostgreSQL schema. + +### Provider stores + +Build the schema for each store with its active driver. Replace local `PRAGMA` and `sqlite_master` reads with the shared helpers. + +Pass every query with source `?` placeholders through the `Rebind` method of the executor. Rebind after `sqlx.In` expands a query. + +Use portable `ON CONFLICT` clauses and boolean literals. Keep existing data models, table names, and provider behavior. + +### Startup regression + +Extend the PostgreSQL boot test beyond the outer `provideServices` error. Assert every affected service or direct store boundary is available. + +## Tests + +| Acceptance criterion | Evidence | +| --- | --- | +| `AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.1` | Package `TestPostgresStoreSchemaReplay` tests and `TestPostgresBootInitializesRepositories` | +| `AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.2` | Each package initializes the same isolated PostgreSQL schema twice and reads preserved rows | +| `AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.3` | Representative PostgreSQL create, read, update, list, and remove operations in each store package | +| `AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.4` | Existing provider initialization error tests and startup log paths | +| `AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.5` | Full PostgreSQL service-graph test plus provider store operation tests | + +## E2E tests + +No browser test is required. The defect occurs before provider HTTP behavior, and the PostgreSQL boot test covers the complete backend construction boundary. + +## Work orders + +- [x] [Task 01: Add portable schema helpers](task-01-portable-schema-helpers.md) +- [x] [Task 02: Port the GitHub store](task-02-github-store.md) +- [x] [Task 03: Port the GitLab store](task-03-gitlab-store.md) +- [x] [Task 04: Port issue intake stores](task-04-issue-intake-stores.md) +- [x] [Task 05: Port the Azure DevOps store](task-05-azure-devops-store.md) +- [x] [Task 06: Port workflow execution stores](task-06-workflow-execution-stores.md) +- [x] [Task 07: Harden PostgreSQL boot coverage](task-07-postgres-boot-coverage.md) + +## Verification results + +- Task 01: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/db/... -run 'Test.*(TimestampType|TableExists|TableColumns)' -v` + passed. +- Task 02: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/github -run '^TestPostgresStore' -v` passed. +- Task 02: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/github` passed. +- Task 03: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/gitlab -run '^TestPostgresStore' -v` passed. +- Task 03 review regression: `KANDEV_TEST_POSTGRES_DSN= go + test -race ./internal/gitlab -run + 'TestPostgresStore|TestMigrateMRWatchUniqueKey_PostgresLegacy' -v` passed. +- Task 03: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/gitlab` passed. +- Task 04: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/jira ./internal/linear ./internal/sentry -run '^TestPostgresStore' + -v` passed. +- Task 04: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/jira ./internal/linear ./internal/sentry` passed. +- Task 05: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/azuredevops -run '^TestPostgresStore' -v` passed. +- Task 05: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/azuredevops` passed. +- Task 06: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/workflowsync ./internal/automation -run '^TestPostgresStore' + -v` passed. +- Task 06: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/workflowsync ./internal/automation` passed. +- Review regression: `KANDEV_TEST_POSTGRES_DSN= go test + -race ./internal/automation ./internal/github ./internal/gitlab -run + 'TestPostgresStore|TestMigrateMRWatchUniqueKey_PostgresLegacy' -v` passed. +- Final affected-package race run across `internal/db/...`, GitHub, GitLab, + Jira, Linear, Sentry, Azure DevOps, workflow sync, automation, and + `backendapp` passed after the review fixes. + +## Risks + +- GitHub and GitLab contain many store methods. A missed query can pass schema tests and fail during later provider activity. +- Boolean columns currently mix boolean and integer expressions. PostgreSQL rejects comparisons between these types. +- SQLite table rebuilds can lose constraints if a portability change alters their statement order. diff --git a/docs/plans/postgres-domain-store-parity/task-01-portable-schema-helpers.md b/docs/plans/postgres-domain-store-parity/task-01-portable-schema-helpers.md new file mode 100644 index 0000000000..269f25cdac --- /dev/null +++ b/docs/plans/postgres-domain-store-parity/task-01-portable-schema-helpers.md @@ -0,0 +1,82 @@ +--- +id: "01-portable-schema-helpers" +title: "Add portable schema helpers" +status: done +wave: 1 +depends_on: [] +plan: "plan.md" +requirements: + - REQ-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001 +acceptance_criteria: + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.1 + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.2 +system_design: + - ../../specs/platform/system-design/postgres-domain-store-parity.md +--- + +# Task 01: Add Portable Schema Helpers + +## Summary + +Add shared helpers for portable timestamp types and schema introspection. These helpers remove provider-owned database detection. + +## In scope + +- Add the timestamp-type helper in `internal/db/dialect`. +- Add table and column introspection helpers in `internal/db`. +- Cover SQLite and PostgreSQL behavior. + +## Out of scope + +- Change a provider store. +- Add a migration framework. + +## Acceptance + +- The timestamp helper returns `DATETIME` for SQLite and `TIMESTAMPTZ` for PostgreSQL. +- Table and column probes use the active database catalog. +- The helpers report absent objects without an error. + +## Verification + +```bash +KANDEV_TEST_POSTGRES_DSN= go test -race ./internal/db/... -run 'Test.*(TimestampType|TableExists|TableColumns)' -v +``` + +## Files likely touched + +- `apps/backend/internal/db/dialect/types.go` +- `apps/backend/internal/db/dialect/dialect_test.go` +- `apps/backend/internal/db/schema.go` +- `apps/backend/internal/db/schema_test.go` +- `apps/backend/internal/db/schema_postgres_test.go` + +## Dependencies + +None. + +## Risks + +- PostgreSQL probes must use `current_schema()` to preserve isolated test schemas. + +## Parallelism + +`sequential` + +## Inputs + +- `docs/decisions/0027-replayable-schema-migrations.md` +- `apps/backend/internal/delivery/store.go` +- `apps/backend/internal/task/repository/sqlite/worktree_ownership_targets.go` + +## Results + +- Added `dialect.TimestampType` for SQLite `DATETIME` and PostgreSQL + `TIMESTAMPTZ` schemas. +- Added shared `db.TableExists`, `db.TableColumns`, and `db.ColumnExists` + probes using the active database catalog and current PostgreSQL schema. +- Added SQLite and environment-gated PostgreSQL coverage for present and + absent tables and columns. +- Verification: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/db/... -run 'Test.*(TimestampType|TableExists|TableColumns)' -v` + passed. diff --git a/docs/plans/postgres-domain-store-parity/task-02-github-store.md b/docs/plans/postgres-domain-store-parity/task-02-github-store.md new file mode 100644 index 0000000000..380c494555 --- /dev/null +++ b/docs/plans/postgres-domain-store-parity/task-02-github-store.md @@ -0,0 +1,92 @@ +--- +id: "02-github-store" +title: "Port the GitHub store" +status: done +wave: 2 +depends_on: + - "01-portable-schema-helpers" +plan: "plan.md" +requirements: + - REQ-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001 +acceptance_criteria: + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.1 + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.2 + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.3 +system_design: + - ../../specs/platform/system-design/postgres-domain-store-parity.md +--- + +# Task 02: Port the GitHub Store + +## Summary + +Make GitHub schema initialization and store operations portable. Add PostgreSQL coverage for authentication, settings, watches, and task pull requests. + +## In scope + +- Build GitHub schema statements with portable types and boolean defaults. +- Replace local schema probes with shared helpers. +- Rebind GitHub store queries and transaction queries. +- Replace SQLite-only conflict syntax. +- Add fresh, replay, and representative operation tests on PostgreSQL. + +## Out of scope + +- Change GitHub API clients or authentication behavior. +- Change table names or stored models. + +## Acceptance + +- `github.NewStore` succeeds twice against one PostgreSQL schema. +- PostgreSQL operations cover workspace connections, watches, task pull requests, and app registrations. +- GitHub store calls do not send unresolved source placeholders to PostgreSQL. + +## Verification + +```bash +KANDEV_TEST_POSTGRES_DSN= go test -race ./internal/github -run 'TestPostgresStore' -v +``` + +## Files likely touched + +- `apps/backend/internal/github/store.go` +- `apps/backend/internal/github/store_connections.go` +- `apps/backend/internal/github/deployment_app_store.go` +- `apps/backend/internal/github/store_task_cleanup.go` +- `apps/backend/internal/github/store_task_pr_ownership.go` +- `apps/backend/internal/github/webhook_service.go` +- `apps/backend/internal/github/store_postgres_test.go` + +## Dependencies + +- Task 01 supplies schema helpers. + +## Risks + +- GitHub has SQLite table rebuilds for historical schemas. Their SQLite behavior must remain unchanged. + +## Parallelism + +`sequential` + +## Inputs + +- `apps/backend/internal/github/store.go` +- Existing GitHub store tests for each listed concept. + +## Results + +- Adapted GitHub schema DDL and migrations to the active driver, including + PostgreSQL timestamp and boolean forms plus replayable registration triggers. +- Reused shared schema probes and rebound GitHub store, transaction, settings, + watch, task PR, authentication, webhook, CI, and statistics queries. +- Replaced SQLite conflict statements with portable `ON CONFLICT` clauses and + preserved the personal/workspace GitHub App registration invariants on both + SQLite and PostgreSQL. +- Added PostgreSQL fresh/replay coverage for connections, personal auth, + settings, watches, task PRs, CI automation, auth flows, statistics, and + trigger enforcement. +- Verification: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/github -run '^TestPostgresStore' -v` passed. +- Verification: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/github` passed. diff --git a/docs/plans/postgres-domain-store-parity/task-03-gitlab-store.md b/docs/plans/postgres-domain-store-parity/task-03-gitlab-store.md new file mode 100644 index 0000000000..c05eab8755 --- /dev/null +++ b/docs/plans/postgres-domain-store-parity/task-03-gitlab-store.md @@ -0,0 +1,98 @@ +--- +id: "03-gitlab-store" +title: "Port the GitLab store" +status: done +wave: 3 +depends_on: + - "02-github-store" +plan: "plan.md" +requirements: + - REQ-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001 +acceptance_criteria: + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.1 + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.2 + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.3 +system_design: + - ../../specs/platform/system-design/postgres-domain-store-parity.md +--- + +# Task 03: Port the GitLab Store + +## Summary + +Make GitLab task and merge-request persistence portable. Add PostgreSQL coverage for settings, watches, links, and automation state. + +## In scope + +- Build GitLab schema statements with portable types and boolean defaults. +- Replace local schema probes with shared helpers. +- Rebind GitLab store queries and transaction queries. +- Add fresh, replay, and representative operation tests on PostgreSQL. + +## Out of scope + +- Change GitLab provider clients or host selection. +- Change merge-request lifecycle behavior. + +## Acceptance + +- `gitlab.NewStore` succeeds twice against one PostgreSQL schema. +- PostgreSQL operations cover settings, watches, task links, and automation state. +- GitLab store calls do not send unresolved source placeholders to PostgreSQL. + +## Verification + +```bash +KANDEV_TEST_POSTGRES_DSN= go test -race ./internal/gitlab -run 'TestPostgresStore' -v +``` + +## Files likely touched + +- `apps/backend/internal/gitlab/store.go` +- `apps/backend/internal/gitlab/store_config.go` +- `apps/backend/internal/gitlab/store_e2e_reset.go` +- `apps/backend/internal/gitlab/store_mr_automation.go` +- `apps/backend/internal/gitlab/store_task_cleanup.go` +- `apps/backend/internal/gitlab/store_task_mr_link.go` +- `apps/backend/internal/gitlab/store_watch_reset.go` +- `apps/backend/internal/gitlab/store_watches.go` +- `apps/backend/internal/gitlab/store_postgres_test.go` + +## Dependencies + +- Task 02 establishes the code-host portability pattern. + +## Risks + +- GitLab stores numeric switches beside boolean columns. Preserve the current model type of each column. + +## Parallelism + +`sequential` + +## Inputs + +- `apps/backend/internal/gitlab/store.go` +- Existing GitLab store tests for each listed concept. + +## Results + +- Adapted GitLab schema DDL and idempotent migrations to the active driver, + including PostgreSQL timestamp and boolean forms. +- Reused shared schema probes and rebound GitLab settings, task-MR, watch, + reservation, reset, cleanup, mention-scope, and automation queries. +- Preserved integer-backed `last_ok` and `draft` columns with explicit CASE + conversion while using boolean literals for PostgreSQL boolean columns. +- Kept the SQLite-only MR-watch table rebuild on SQLite and added a + transaction-safe PostgreSQL migration for legacy two-column MR-watch unique + constraints. +- Added PostgreSQL fresh/replay coverage for settings, mention scope, task + links, automation checkpoints, MR watches, review/issue watches, dedup + reservations, and action presets. +- Added a PostgreSQL legacy-schema upgrade test that calls `EnsureMRWatch` for + two branches on one session and repository. +- Verification: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/gitlab -run 'TestPostgresStore|TestMigrateMRWatchUniqueKey_PostgresLegacy' + -v` passed. +- Verification: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/gitlab` passed. diff --git a/docs/plans/postgres-domain-store-parity/task-04-issue-intake-stores.md b/docs/plans/postgres-domain-store-parity/task-04-issue-intake-stores.md new file mode 100644 index 0000000000..fe36d01fdf --- /dev/null +++ b/docs/plans/postgres-domain-store-parity/task-04-issue-intake-stores.md @@ -0,0 +1,97 @@ +--- +id: "04-issue-intake-stores" +title: "Port issue intake stores" +status: done +wave: 4 +depends_on: + - "03-gitlab-store" +plan: "plan.md" +requirements: + - REQ-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001 +acceptance_criteria: + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.1 + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.2 + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.3 +system_design: + - ../../specs/platform/system-design/postgres-domain-store-parity.md +--- + +# Task 04: Port Issue Intake Stores + +## Summary + +Make Jira, Linear, and Sentry stores portable. These stores share settings, health, watch, and reservation patterns. + +## In scope + +- Use portable schema types and shared schema probes. +- Rebind store and transaction queries. +- Replace SQLite-only reservation syntax. +- Add fresh, replay, settings, watch, and reservation tests on PostgreSQL. + +## Out of scope + +- Change provider polling or external issue filters. +- Change workspace ownership rules. + +## Acceptance + +- Each `NewStore` succeeds twice against its PostgreSQL schema. +- Settings, health, watch, and reservation operations succeed on PostgreSQL. +- SQLite legacy migrations keep their current data-preservation behavior. + +## Verification + +```bash +KANDEV_TEST_POSTGRES_DSN= go test -race ./internal/jira ./internal/linear ./internal/sentry -run 'TestPostgresStore' -v +``` + +## Files likely touched + +- `apps/backend/internal/jira/store.go` +- `apps/backend/internal/jira/store_postgres_test.go` +- `apps/backend/internal/linear/store.go` +- `apps/backend/internal/linear/store_issue_watch.go` +- `apps/backend/internal/linear/store_postgres_test.go` +- `apps/backend/internal/sentry/store.go` +- `apps/backend/internal/sentry/store_issue_watch.go` +- `apps/backend/internal/sentry/store_postgres_test.go` + +## Dependencies + +- Task 03 completes the code-host store conversions. + +## Risks + +- Sentry uses guarded table rebuilds for multi-instance settings. PostgreSQL replay must not enter SQLite rebuild paths. + +## Parallelism + +`sequential` + +## Inputs + +- Jira, Linear, and Sentry store tests. +- `apps/backend/internal/integrations/AGENTS.md` + +## Results + +- Adapted Jira, Linear, and Sentry schema DDL and additive migrations to the + active driver, including PostgreSQL timestamp and boolean forms. +- Reused shared schema probes and rebound store and transaction queries across + configuration, health, watches, resets, and reservations. +- Replaced SQLite-only `INSERT OR IGNORE` reservation statements with + portable `ON CONFLICT ... DO NOTHING` clauses. +- Kept the Jira/Linear singleton migrations and Sentry instance/watch rebuilds + on SQLite, so PostgreSQL startup does not enter SQLite catalog or PRAGMA + paths. +- Preserved integer-backed health flags with explicit CASE conversion and + retained Sentry duplicate/FK error mapping on PostgreSQL. +- Added PostgreSQL fresh/replay coverage for settings, health, watches, + instance binding, FK protection, and reservation operations in all three + packages. +- Verification: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/jira ./internal/linear ./internal/sentry -run 'TestPostgresStore' + -v` passed. +- Verification: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/jira ./internal/linear ./internal/sentry` passed. diff --git a/docs/plans/postgres-domain-store-parity/task-05-azure-devops-store.md b/docs/plans/postgres-domain-store-parity/task-05-azure-devops-store.md new file mode 100644 index 0000000000..6484194007 --- /dev/null +++ b/docs/plans/postgres-domain-store-parity/task-05-azure-devops-store.md @@ -0,0 +1,90 @@ +--- +id: "05-azure-devops-store" +title: "Port the Azure DevOps store" +status: done +wave: 5 +depends_on: + - "04-issue-intake-stores" +plan: "plan.md" +requirements: + - REQ-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001 +acceptance_criteria: + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.1 + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.2 + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.3 +system_design: + - ../../specs/platform/system-design/postgres-domain-store-parity.md +--- + +# Task 05: Port the Azure DevOps Store + +## Summary + +Make Azure DevOps settings, task links, and watcher persistence portable. Add PostgreSQL coverage for each stored surface. + +## In scope + +- Build schema statements with portable timestamp types and boolean defaults. +- Replace local schema probes with shared helpers. +- Rebind settings, task-link, watcher, reset, and reservation queries. +- Add fresh, replay, and representative operation tests on PostgreSQL. + +## Out of scope + +- Change Azure DevOps REST behavior. +- Change board or work-item models. + +## Acceptance + +- `azuredevops.NewStore` succeeds twice against one PostgreSQL schema. +- Settings, task links, watches, resets, and reservations succeed on PostgreSQL. +- Azure DevOps store calls do not send unresolved source placeholders to PostgreSQL. + +## Verification + +```bash +KANDEV_TEST_POSTGRES_DSN= go test -race ./internal/azuredevops -run 'TestPostgresStore' -v +``` + +## Files likely touched + +- `apps/backend/internal/azuredevops/store.go` +- `apps/backend/internal/azuredevops/store_task_pr.go` +- `apps/backend/internal/azuredevops/store_task_work_item.go` +- `apps/backend/internal/azuredevops/store_watch_reset.go` +- `apps/backend/internal/azuredevops/watch_store.go` +- `apps/backend/internal/azuredevops/store_postgres_test.go` + +## Dependencies + +- Task 04 supplies the watcher-store portability pattern. + +## Risks + +- Watch reset transactions combine dynamic table names and placeholders. Rebind only values, not validated identifiers. + +## Parallelism + +`sequential` + +## Inputs + +- `docs/specs/integrations/system-design/azure-devops-integration-01.md` +- Existing Azure DevOps store tests. + +## Results + +- Adapted Azure DevOps schema DDL and additive migrations to the active + driver, including PostgreSQL timestamp and boolean forms. +- Reused shared schema probes and rebound Azure DevOps settings, saved-view, + task-link, watcher, reservation, and reset queries at their database or + transaction boundary. +- Preserved validated dynamic table identifiers while rebinding only query + values in watcher reset transactions. +- Added PostgreSQL fresh/replay coverage for configuration health, saved + views, settings, task PR/work-item links, watcher reservations, assignment, + reset, workspace deletion, and cleanup operations. +- Verification: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/azuredevops -run 'TestPostgresStore' -v` passed. +- Verification: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/azuredevops` passed. diff --git a/docs/plans/postgres-domain-store-parity/task-06-workflow-execution-stores.md b/docs/plans/postgres-domain-store-parity/task-06-workflow-execution-stores.md new file mode 100644 index 0000000000..be96ee63bf --- /dev/null +++ b/docs/plans/postgres-domain-store-parity/task-06-workflow-execution-stores.md @@ -0,0 +1,92 @@ +--- +id: "06-workflow-execution-stores" +title: "Port workflow execution stores" +status: done +wave: 6 +depends_on: + - "05-azure-devops-store" +plan: "plan.md" +requirements: + - REQ-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001 +acceptance_criteria: + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.1 + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.2 + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.3 +system_design: + - ../../specs/platform/system-design/postgres-domain-store-parity.md +--- + +# Task 06: Port Workflow Execution Stores + +## Summary + +Make workflow sync and automation persistence portable. Cover settings, triggers, repositories, runs, and cleanup jobs on PostgreSQL. + +## In scope + +- Build schema statements with portable timestamp types and boolean defaults. +- Rebind workflow sync and automation queries. +- Replace SQLite-only conflict syntax. +- Add fresh, replay, and representative operation tests on PostgreSQL. + +## Out of scope + +- Change workflow synchronization behavior. +- Change automation scheduling or task creation. + +## Acceptance + +- Both stores initialize twice against their PostgreSQL schemas. +- Workflow sync settings and automation lifecycle operations succeed on PostgreSQL. +- Automation read transactions rebind expanded list queries after `sqlx.In`. + +## Verification + +```bash +KANDEV_TEST_POSTGRES_DSN= go test -race ./internal/workflowsync ./internal/automation -run 'TestPostgresStore' -v +``` + +## Files likely touched + +- `apps/backend/internal/workflowsync/store.go` +- `apps/backend/internal/workflowsync/store_postgres_test.go` +- `apps/backend/internal/automation/store.go` +- `apps/backend/internal/automation/export_store.go` +- `apps/backend/internal/automation/run_retention.go` +- `apps/backend/internal/automation/store_postgres_test.go` + +## Dependencies + +- Task 05 completes provider store conversion. + +## Risks + +- Automation joins core task tables. Tests must use the real repository startup order for prerequisite schemas. + +## Parallelism + +`sequential` + +## Inputs + +- Existing workflow sync and automation store tests. +- `apps/backend/internal/backendapp/postgres_boot_test.go` + +## Results + +- Adapted workflow-sync and automation schema DDL to the active driver, + including PostgreSQL timestamp and boolean forms. +- Rebound workflow-sync and automation reads, writes, transactions, dynamic + run projections, and retention queries at the executing database boundary. +- Replaced the automation repository backfill's SQLite-only conflict syntax + with a portable `ON CONFLICT ... DO NOTHING` clause. +- Preserved task-state joins and isolated-test fallbacks while using + integer predicates for the shared `task_sessions.is_primary` column. +- Added PostgreSQL fresh/replay coverage for workflow settings, automation + repositories, triggers, runs, run summaries, retention checks, and cleanup + jobs. +- Verification: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/workflowsync ./internal/automation -run 'TestPostgresStore' + -v` passed. +- Verification: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/workflowsync ./internal/automation` passed. diff --git a/docs/plans/postgres-domain-store-parity/task-07-postgres-boot-coverage.md b/docs/plans/postgres-domain-store-parity/task-07-postgres-boot-coverage.md new file mode 100644 index 0000000000..7994646147 --- /dev/null +++ b/docs/plans/postgres-domain-store-parity/task-07-postgres-boot-coverage.md @@ -0,0 +1,82 @@ +--- +id: "07-postgres-boot-coverage" +title: "Harden PostgreSQL boot coverage" +status: done +wave: 7 +depends_on: + - "06-workflow-execution-stores" +plan: "plan.md" +requirements: + - REQ-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001 +acceptance_criteria: + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.1 + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.4 + - AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.5 +system_design: + - ../../specs/platform/system-design/postgres-domain-store-parity.md +--- + +# Task 07: Harden PostgreSQL Boot Coverage + +## Summary + +Make the full PostgreSQL boot test fail when an affected service or store is unavailable. Record the final package results in the plan. + +## In scope + +- Assert availability for GitHub, GitLab persistence, Jira, Linear, Sentry, Azure DevOps, workflow sync, and automation. +- Preserve nonfatal provider isolation in production startup. +- Run the focused PostgreSQL package tests in the CI-shaped environment. + +## Out of scope + +- Make one provider error stop the complete backend. +- Add browser automation for a backend startup defect. + +## Acceptance + +- The old code fails the strengthened boot test because affected stores are unavailable. +- The corrected code creates the full affected service graph on PostgreSQL. +- The plan records every focused command and result. + +## Verification + +```bash +KANDEV_TEST_POSTGRES_DSN= go test -race ./internal/backendapp -run '^TestPostgresBootInitializesRepositories$' -v +``` + +## Files likely touched + +- `apps/backend/internal/backendapp/postgres_boot_test.go` +- `docs/plans/postgres-domain-store-parity/plan.md` +- `docs/plans/postgres-domain-store-parity/task-07-postgres-boot-coverage.md` + +## Dependencies + +- Tasks 01 through 06 complete all store conversions. + +## Risks + +- GitLab can construct its outer service while its task store is absent. The test must exercise or inspect that store boundary. + +## Parallelism + +`sequential` + +## Inputs + +- `apps/backend/internal/backendapp/services.go` +- `apps/backend/internal/backendapp/postgres_boot_test.go` + +## Results + +- Strengthened the PostgreSQL boot test to require every affected provider + service and the workflow-sync and automation components. +- Added store-backed reads for GitHub, GitLab, Jira, Linear, Sentry, Azure + DevOps, and workflow sync so a service cannot pass only because its outer + constructor returned a non-nil value. +- Checked the automation component and service boundary directly while + preserving nonfatal provider initialization behavior in production. +- Verification: `KANDEV_TEST_POSTGRES_DSN= go test -race + ./internal/backendapp -run '^TestPostgresBootInitializesRepositories$' -v` + passed. diff --git a/docs/specs/platform/README.md b/docs/specs/platform/README.md index cc1da68032..8791f98a32 100644 --- a/docs/specs/platform/README.md +++ b/docs/specs/platform/README.md @@ -59,6 +59,7 @@ localization, feature toggles, health, and shared session recovery services. - [Session MCP Attachment Observability](requirements/mcp-session-observability.md) - [Mid-Turn Steering](requirements/mid-turn-steering.md) - [Semantic Notifications](requirements/notifications.md) +- [PostgreSQL Domain Store Parity](requirements/postgres-domain-store-parity.md) - [Provider Error Recovery](requirements/provider-error-recovery.md) - [Session Config Reconciliation Across Agent Types](requirements/session-config-cross-agent-reconcile.md) - [Session subscription recovery](requirements/session-subscription-recovery.md) @@ -90,6 +91,7 @@ localization, feature toggles, health, and shared session recovery services. - [LSP File Intelligence System Design Part 1](system-design/lsp-file-intelligence-01.md) - [LSP File Intelligence System Design Part 2](system-design/lsp-file-intelligence-02.md) - [Session MCP Attachment Observability](system-design/mcp-session-observability.md) +- [PostgreSQL Domain Store Parity](system-design/postgres-domain-store-parity.md) - [Provider Error Recovery](system-design/provider-error-recovery.md) - [Workspace Git Status](system-design/workspace-git-status.md) - [Go dev launcher and startup version](system-design/go-dev-launcher.md) diff --git a/docs/specs/platform/requirements/postgres-domain-store-parity.md b/docs/specs/platform/requirements/postgres-domain-store-parity.md new file mode 100644 index 0000000000..b5d6c197c1 --- /dev/null +++ b/docs/specs/platform/requirements/postgres-domain-store-parity.md @@ -0,0 +1,41 @@ +--- +status: active +system: platform +created: 2026-09-03 +owners: + - kandev +--- + +# PostgreSQL Domain Store Parity Requirements + +## Overview + +Kandev supports SQLite and PostgreSQL as database backends. The Platform system owns this shared operational guarantee. + +Built-in domain services must remain available with either supported backend. A database dialect must not silently disable a configured service during startup. + +## Terminology + +- **Domain store:** A store that persists state for one built-in service in the shared Kandev database. +- **Replay:** A second schema initialization against the same database without a version change. + +## Requirements + +### REQ-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001: Portable domain stores + +**Intent:** Operators can use all built-in persisted services when Kandev uses PostgreSQL. + +#### Acceptance criteria + +- **AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.1:** When Kandev starts with PostgreSQL, every enabled built-in domain store shall initialize successfully. +- **AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.2:** When schema initialization runs again, each domain store shall preserve its data and return no replay error. +- **AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.3:** When a service reads or changes PostgreSQL data, its result shall match the equivalent SQLite operation. +- **AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.4:** When a domain store cannot initialize, startup diagnostics shall identify that store and the database error. +- **AC-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001.5:** When PostgreSQL is active, integration and automation endpoints shall not fail because their stores are unavailable. + +## Out of scope + +- Active-active backend replicas that share one PostgreSQL database. +- Automatic PostgreSQL backups or restores. +- A central migration framework. +- Changes to provider authentication or external provider APIs. diff --git a/docs/specs/platform/system-design/postgres-domain-store-parity.md b/docs/specs/platform/system-design/postgres-domain-store-parity.md new file mode 100644 index 0000000000..01b04d8459 --- /dev/null +++ b/docs/specs/platform/system-design/postgres-domain-store-parity.md @@ -0,0 +1,76 @@ +--- +status: current +system: platform +requirements: + - REQ-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001 +--- + +# PostgreSQL Domain Store Parity System Design + +## Purpose and boundaries + +The Platform system owns database portability because it is a shared startup guarantee. Integration and automation services consume this guarantee. + +This design covers GitHub, GitLab, Jira, Linear, Sentry, Azure DevOps, workflow sync, and automation stores. It does not change provider behavior. + +## Requirement mapping + +| Requirement | Design sections | +| --- | --- | +| `REQ-PLATFORM-POSTGRES-DOMAIN-STORE-PARITY-001` | [Schema contract](#schema-contract), [Query contract](#query-contract), [Startup contract](#startup-contract), [Verification strategy](#verification-strategy) | + +## Components and responsibilities + +- `internal/db/dialect` supplies SQL types and fragments for each supported database. +- `internal/db` supplies shared schema-introspection helpers. +- Each domain store owns its tables, ordered upgrade steps, and store methods. +- `internal/backendapp` creates the stores and keeps provider errors isolated from unrelated services. + +The shared helpers replace local copies of `PRAGMA` and `sqlite_master` probes. This boundary keeps database detection out of provider packages. + +## Schema contract + +Each schema owner builds data-definition statements for the active driver. SQLite uses `DATETIME`. PostgreSQL uses `TIMESTAMPTZ`. + +Boolean defaults and predicates use SQL boolean literals. Integer status fields remain integers when their model contract is numeric. + +Schema introspection uses the current PostgreSQL schema. SQLite introspection uses its native catalog and table-info interface. + +Each store applies the same ordered initialization on a fresh database and during replay. SQLite-only table rebuilds run only when SQLite needs them. + +## Query contract + +Store queries use `?` as the source placeholder syntax. The final database or transaction executor calls `Rebind` before execution. + +Queries built with `sqlx.In` call `Rebind` after expansion. Store code does not send unresolved `?` placeholders to PostgreSQL. + +Portable conflict handling uses `ON CONFLICT`. Store code does not use `INSERT OR IGNORE` in shared database paths. + +SQL predicates compare boolean columns with `TRUE` or `FALSE`. Bound values use Go booleans for boolean columns. + +## Startup contract + +Provider initialization errors remain isolated. One unavailable provider does not stop unrelated Kandev services. + +The PostgreSQL boot test must also assert service availability. A successful outer startup call is not sufficient because provider errors are nonfatal. + +GitLab has a separate host store and task store. PostgreSQL evidence must cover the task store even when the outer service exists. + +## Failure and recovery + +A schema or query error returns through the owning store. Existing startup logs keep the store name and database error. + +Schema replay does not remove data. PostgreSQL operators keep responsibility for database backups before an upgrade. + +## Verification strategy + +Each affected package uses `testutil.OpenIsolatedPostgres` for fresh-schema, replay, and representative store operations. SQLite package tests keep their current coverage. + +The backend boot test creates the full service graph on PostgreSQL. It asserts availability for every affected service and store boundary. + +Provider tests cover settings, watches, task links, and automation state where those concepts exist. These tests expose placeholder and boolean-type errors after startup. + +## Related decisions + +- [Replayable schema migrations across SQLite and Postgres](../../../decisions/0027-replayable-schema-migrations.md) +- [Workspace-scoped integration settings](../../../decisions/0030-workspace-scoped-integration-settings.md)