Files
coder/coderd/database/gen/dump/main.go
Hugo Dutka 1bfa7d42e8 chore: add postgres template caching for tests (#15336)
This PR is the first in a series aimed at closing
[#15109](https://github.com/coder/coder/issues/15109).

### Changes

- **Template Database Creation:**  
`dbtestutil.Open` now has the ability to create a template database if
none is provided via `DB_FROM`. The template database’s name is derived
from a hash of the migration files, ensuring that it can be reused
across tests and is automatically updated whenever migrations change.

- **Optimized Database Handling:**  
Previously, `dbtestutil.Open` would spin up a new container for each
test when `DB_FROM` was unset. Now, it first checks for an active
PostgreSQL instance on `localhost:5432`. If none is found, it creates a
single container that remains available for subsequent tests,
eliminating repeated container startups.

These changes address the long individual test times (10+ seconds)
reported by some users, likely due to the time Docker took to start and
complete migrations.
2024-11-04 17:23:31 +01:00

70 lines
1.2 KiB
Go

package main
import (
"database/sql"
"fmt"
"os"
"path/filepath"
"runtime"
"github.com/coder/coder/v2/coderd/database/dbtestutil"
"github.com/coder/coder/v2/coderd/database/migrations"
)
var preamble = []byte("-- Code generated by 'make coderd/database/generate'. DO NOT EDIT.")
type mockTB struct {
cleanup []func()
}
func (t *mockTB) Cleanup(f func()) {
t.cleanup = append(t.cleanup, f)
}
func (*mockTB) Helper() {
// noop
}
func (*mockTB) Logf(format string, args ...any) {
_, _ = fmt.Printf(format, args...)
}
func main() {
t := &mockTB{}
defer func() {
for _, f := range t.cleanup {
f()
}
}()
connection, err := dbtestutil.Open(t)
if err != nil {
panic(err)
}
db, err := sql.Open("postgres", connection)
if err != nil {
panic(err)
}
defer db.Close()
err = migrations.Up(db)
if err != nil {
panic(err)
}
dumpBytes, err := dbtestutil.PGDumpSchemaOnly(connection)
if err != nil {
panic(err)
}
_, mainPath, _, ok := runtime.Caller(0)
if !ok {
panic("couldn't get caller path")
}
err = os.WriteFile(filepath.Join(mainPath, "..", "..", "..", "dump.sql"), append(preamble, dumpBytes...), 0o600)
if err != nil {
panic(err)
}
}