From b71fcc2e0040bbdf0a4212c48e8681e1a60e9e67 Mon Sep 17 00:00:00 2001 From: Simon Ser Date: Mon, 3 Aug 2020 18:43:15 +0200 Subject: [PATCH] Add DB.DeleteUser --- db.go | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/db.go b/db.go index 5c54fbc..b18b73e 100644 --- a/db.go +++ b/db.go @@ -250,6 +250,40 @@ func (db *DB) StoreUser(user *User) error { return err } +func (db *DB) DeleteUser(username string) error { + db.lock.Lock() + defer db.lock.Unlock() + + tx, err := db.db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + + _, err = tx.Exec(`DELETE FROM Channel + WHERE id IN ( + SELECT Channel.id + FROM Channel + JOIN Network ON Channel.network = Network.id + WHERE Network.user = ? + )`, username) + if err != nil { + return err + } + + _, err = tx.Exec("DELETE FROM Network WHERE user = ?", username) + if err != nil { + return err + } + + _, err = tx.Exec("DELETE FROM User WHERE username = ?", username) + if err != nil { + return err + } + + return tx.Commit() +} + func (db *DB) ListNetworks(username string) ([]Network, error) { db.lock.RLock() defer db.lock.RUnlock() @@ -359,12 +393,12 @@ func (db *DB) DeleteNetwork(id int64) error { } defer tx.Rollback() - _, err = tx.Exec("DELETE FROM Network WHERE id = ?", id) + _, err = tx.Exec("DELETE FROM Channel WHERE network = ?", id) if err != nil { return err } - _, err = tx.Exec("DELETE FROM Channel WHERE network = ?", id) + _, err = tx.Exec("DELETE FROM Network WHERE id = ?", id) if err != nil { return err }