Add reset-db task to reset the development database

This commit is contained in:
Luis Eduardo Jeréz Girón
2024-07-19 23:45:37 -06:00
parent 36681c0776
commit 54842091e5
2 changed files with 58 additions and 0 deletions

55
cmd/resetdb/main.go Normal file
View File

@@ -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
}

View File

@@ -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/.