feat: add automatic database migration recovery to scripts/develop (#23466)

When developers switch branches, the database may have migrations
from the other branch that don't exist in the current binary.
This causes coder server to fail at startup, leaving developers
stuck.

The develop script now detects this before starting the server:

1. Connects to postgres (starts temp embedded instance for
   built-in postgres, or uses CODER_PG_CONNECTION_URL).
2. Compares DB version against the source's latest migration.
3. If DB is ahead, searches git history for the missing down
   SQL files and applies them in a transaction.
4. If git recovery fails (ambiguous versions across branches,
   missing files), falls back to resetting the public schema.

Also adds --reset-db and --skip-db-recovery flags.
This commit is contained in:
Mathias Fredriksson
2026-03-24 22:04:56 +02:00
committed by GitHub
parent 798a6673c6
commit 78b18e72bf
4 changed files with 748 additions and 0 deletions
+47
View File
@@ -0,0 +1,47 @@
//go:build !windows
package main
import (
"os"
"path/filepath"
"strconv"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestCleanStalePIDFile(t *testing.T) {
t.Parallel()
t.Run("NoPIDFile", func(t *testing.T) {
t.Parallel()
cleanStalePIDFile(t.TempDir())
})
t.Run("StalePID", func(t *testing.T) {
t.Parallel()
dir := t.TempDir()
pidFile := filepath.Join(dir, "postmaster.pid")
require.NoError(t, os.WriteFile(pidFile, []byte("999999999\n"), 0o600))
cleanStalePIDFile(dir)
_, err := os.Stat(pidFile)
assert.True(t, os.IsNotExist(err))
})
t.Run("RunningPID", func(t *testing.T) {
t.Parallel()
dir := t.TempDir()
pidFile := filepath.Join(dir, "postmaster.pid")
require.NoError(t, os.WriteFile(pidFile,
[]byte(strconv.Itoa(os.Getpid())+"\n"), 0o600))
cleanStalePIDFile(dir)
_, err := os.Stat(pidFile)
assert.NoError(t, err, "should not remove PID file for running process")
})
}