diff --git a/cmd/resetdb/main.go b/cmd/resetdb/main.go new file mode 100644 index 0000000..4d7bc46 --- /dev/null +++ b/cmd/resetdb/main.go @@ -0,0 +1,55 @@ +package main + +import ( + "database/sql" + "fmt" + "log" + + "github.com/eduardolat/pgbackweb/internal/config" + _ "github.com/lib/pq" +) + +func main() { + log.Println("Are you sure you want to reset the database? (yes/no)") + var answer string + + for answer != "yes" && answer != "no" { + fmt.Scanln(&answer) + if answer == "no" { + log.Println("Exiting...") + return + } + if answer == "yes" { + log.Println("Resetting database...") + break + } + log.Println("Please enter 'yes' or 'no'") + } + + env := config.GetEnv() + db := connectDB(env) + + _, err := db.Exec("DROP SCHEMA public CASCADE; CREATE SCHEMA public;") + if err != nil { + panic(fmt.Errorf("❌ Could not reset DB: %w", err)) + } + + log.Println("✅ Database reset") +} + +func connectDB(env *config.Env) *sql.DB { + db, err := sql.Open("postgres", *env.PBW_POSTGRES_CONN_STRING) + if err != nil { + panic(fmt.Errorf("❌ Could not connect to DB: %w", err)) + } + + err = db.Ping() + if err != nil { + panic(fmt.Errorf("❌ Could not ping DB: %w", err)) + } + + db.SetMaxOpenConns(1) + log.Println("✅ Connected to DB") + + return db +} diff --git a/taskfile.yaml b/taskfile.yaml index d40b9cd..ff2aa3c 100644 --- a/taskfile.yaml +++ b/taskfile.yaml @@ -55,3 +55,6 @@ tasks: fixperms: # Fixes the permissions of the files in the project cmd: ./scripts/fixperms.sh + + reset-db: + cmd: go run ./cmd/resetdb/.