// Package sqldbtest gives tests a database of their own: a SQLite file in a // temporary directory, or, when KEEPORG_TEST_POSTGRES names a PostgreSQL // server, a fresh database on it that is dropped afterwards. Every test that // goes through here runs against PostgreSQL by setting one variable. package sqldbtest import ( "context" "database/sql" "net/url" "os" "path/filepath" "testing" "cc.tiredsysadmin.keeporg/internal/secret" _ "github.com/jackc/pgx/v5/stdlib" ) // PostgresEnv names the PostgreSQL server tests use instead of SQLite, as a // URL whose user may create databases. const PostgresEnv = "KEEPORG_TEST_POSTGRES" // URL returns a database URL that is empty and private to t. func URL(t testing.TB) string { t.Helper() admin := os.Getenv(PostgresEnv) if admin == "" { return "sqlite:" + filepath.Join(t.TempDir(), "keeporg.db") } u, err := url.Parse(admin) if err != nil { t.Fatalf("%s: %v", PostgresEnv, err) } name := "keeporg_test_" + secret.ID() db, err := sql.Open("pgx", admin) if err != nil { t.Fatal(err) } ctx := context.Background() if _, err := db.ExecContext(ctx, "CREATE DATABASE "+name); err != nil { db.Close() t.Fatalf("create test database: %v", err) } t.Cleanup(func() { _, _ = db.ExecContext(ctx, "DROP DATABASE IF EXISTS "+name+" WITH (FORCE)") db.Close() }) u.Path = "/" + name return u.String() }