2023-10-03 16:02:23 +00:00
|
|
|
package postgres
|
2023-09-21 04:01:13 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"os"
|
2024-01-03 02:35:04 +00:00
|
|
|
|
|
|
|
"github.com/avast/retry-go/v4"
|
2023-09-21 04:01:13 +00:00
|
|
|
)
|
|
|
|
|
2023-10-05 07:27:59 +00:00
|
|
|
var dbUrlTemplate = "postgres://postgres@localhost:%s/%s?sslmode=disable"
|
2023-09-21 04:01:13 +00:00
|
|
|
|
|
|
|
func ResetDefaultTestPostgresDB(dropDBUrl string) error {
|
2023-10-03 16:02:23 +00:00
|
|
|
db, err := sql.Open("pgx", dropDBUrl)
|
2023-09-21 04:01:13 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
deletePrevConnectionsSql := `
|
|
|
|
SELECT pid, pg_terminate_backend(pid)
|
|
|
|
FROM pg_stat_activity
|
|
|
|
WHERE datname in ('template1', 'postgres') AND pid <> pg_backend_pid();`
|
|
|
|
_, err = db.Exec(deletePrevConnectionsSql)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = db.Exec("DROP DATABASE IF EXISTS postgres;")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = db.Exec("CREATE DATABASE postgres;")
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewMockPgDB() *sql.DB {
|
|
|
|
mockPgDBPort := os.Getenv("TEST_DB_PORT")
|
2023-11-20 12:51:29 +00:00
|
|
|
if mockPgDBPort == "" {
|
|
|
|
mockPgDBPort = "5432"
|
|
|
|
}
|
2023-09-21 04:01:13 +00:00
|
|
|
//
|
2024-01-03 02:35:04 +00:00
|
|
|
err := retry.Do(
|
|
|
|
func() error {
|
|
|
|
|
|
|
|
dropDBUrl := fmt.Sprintf(dbUrlTemplate, mockPgDBPort, "template1")
|
|
|
|
if err := ResetDefaultTestPostgresDB(dropDBUrl); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}, retry.Attempts(3))
|
|
|
|
if err != nil {
|
2023-10-03 16:02:23 +00:00
|
|
|
log.Fatalf("an error '%s' while reseting the db", err)
|
2023-09-21 04:01:13 +00:00
|
|
|
}
|
|
|
|
mockDBUrl := fmt.Sprintf(dbUrlTemplate, mockPgDBPort, "postgres")
|
|
|
|
db, err := sql.Open("pgx", mockDBUrl)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
|
|
|
|
}
|
|
|
|
return db
|
|
|
|
}
|