added db setup and reset endpoints
This commit is contained in:
parent
18eef141d3
commit
a66aa29275
|
@ -4,6 +4,7 @@ import (
|
|||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
@ -39,6 +40,64 @@ func ConnectToDb() (*pgxpool.Pool, error) {
|
|||
return pool, nil
|
||||
}
|
||||
|
||||
// setup demo db
|
||||
func SetupDemoDb(w http.ResponseWriter, r *http.Request) {
|
||||
// create table and insert demo data
|
||||
createTableSQL := `
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
username VARCHAR(50) UNIQUE NOT NULL,
|
||||
email VARCHAR(100) NOT NULL
|
||||
);`
|
||||
|
||||
// also avoid duplicate entries
|
||||
insertDataSQL := `
|
||||
INSERT INTO users (username, email) VALUES
|
||||
('alice', 'alice@example.com'),
|
||||
('bob', 'bob@example.com'),
|
||||
('charlie', 'charlie@example.com')
|
||||
ON CONFLICT (username) DO NOTHING;`
|
||||
|
||||
// execute create table
|
||||
_, err := DbPool.Exec(context.Background(), createTableSQL)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to create table", http.StatusInternalServerError)
|
||||
log.Printf("Error creating table: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// execute insert demo data
|
||||
_, err = DbPool.Exec(context.Background(), insertDataSQL)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to insert demo data", http.StatusInternalServerError)
|
||||
log.Printf("Error inserting demo data: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
// response back to client
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("Database setup complete with demo data"))
|
||||
log.Println("Demo database setup completed successfully")
|
||||
}
|
||||
|
||||
// nuke the db
|
||||
func NukeDb(w http.ResponseWriter, r *http.Request) {
|
||||
// drop user table
|
||||
dropTableSQL := `
|
||||
DROP TABLE IF EXISTS users CASCADE;
|
||||
`
|
||||
|
||||
// execute the command
|
||||
_, err := DbPool.Exec(context.Background(), dropTableSQL)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to drop table", http.StatusInternalServerError)
|
||||
log.Printf("Error dropping table: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
log.Println("Database nuked")
|
||||
}
|
||||
|
||||
// fetch existing usernames from db
|
||||
func FetchUsernames() (map[string]bool, error) {
|
||||
usernames := make(map[string]bool)
|
||||
|
|
Loading…
Reference in a new issue