@@ -53,7 +53,7 @@ db.exec(`
5353 location TEXT NOT NULL,
5454 date TEXT NOT NULL,
5555 host_user_id TEXT NOT NULL,
56- FOREIGN KEY (host_user_id) REFERENCES users(id)
56+ FOREIGN KEY (host_user_id) REFERENCES users(id) ON DELETE CASCADE
5757 );
5858
5959 CREATE TABLE IF NOT EXISTS catalog_items (
@@ -70,7 +70,7 @@ db.exec(`
7070 total_amount REAL NOT NULL,
7171 created_at TEXT NOT NULL,
7272 FOREIGN KEY (spot_id) REFERENCES spots(id),
73- FOREIGN KEY (user_id) REFERENCES users(id)
73+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
7474 );
7575
7676 CREATE TABLE IF NOT EXISTS order_items (
@@ -160,6 +160,9 @@ const userExistsStatement = db.prepare('SELECT 1 AS found FROM users WHERE id =
160160const spotExistsStatement = db . prepare ( 'SELECT 1 AS found FROM spots WHERE id = ? LIMIT 1' ) ;
161161const getUserByUsernameStatement = db . prepare ( 'SELECT id, username, password, name, role FROM users WHERE username = ?' ) ;
162162const updateUserPasswordStatement = db . prepare ( 'UPDATE users SET password = ? WHERE id = ?' ) ;
163+ const deleteUserByIdStatement = db . prepare ( 'DELETE FROM users WHERE id = ?' ) ;
164+ const deleteOrdersByUserIdStatement = db . prepare ( 'DELETE FROM orders WHERE user_id = ?' ) ;
165+ const deleteSpotsByHostUserIdStatement = db . prepare ( 'DELETE FROM spots WHERE host_user_id = ?' ) ;
163166
164167export const database = {
165168 getUserByCredentials ( username , password ) {
@@ -303,6 +306,21 @@ export const database = {
303306 } ;
304307 } ,
305308
309+ deleteUserCompletely ( userId ) {
310+ db . exec ( 'BEGIN' ) ;
311+
312+ try {
313+ deleteOrdersByUserIdStatement . run ( userId ) ;
314+ deleteSpotsByHostUserIdStatement . run ( userId ) ;
315+ deleteUserByIdStatement . run ( userId ) ;
316+
317+ db . exec ( 'COMMIT' ) ;
318+ } catch ( error ) {
319+ db . exec ( 'ROLLBACK' ) ;
320+ throw error ;
321+ }
322+ } ,
323+
306324 getBillBySpotId ( spotId ) {
307325 const summaryRows = db
308326 . prepare (
0 commit comments