summary refs log tree commit diff
diff options
context:
space:
mode:
authorFlam3rboy <34555296+Flam3rboy@users.noreply.github.com>2021-09-20 21:27:08 +0200
committerGitHub <noreply@github.com>2021-09-20 21:27:08 +0200
commitfe34c5da8747022ce568ea43deb002fade3b5faa (patch)
tree6ebbfa513b52428562138cc8b765c41f86f137ee
parentMerge pull request #386 from ChrisChrome/master (diff)
parent:bug: fix .delete -> add onDelete: "CASCADE" (diff)
downloadserver-fe34c5da8747022ce568ea43deb002fade3b5faa.tar.xz
Merge pull request #382 from fosscord/auto-delete-relations
Auto delete relations
-rw-r--r--api/src/routes/channels/#channel_id/index.ts20
-rw-r--r--api/src/routes/channels/#channel_id/messages/#message_id/index.ts3
-rw-r--r--api/src/routes/guilds/#guild_id/delete.ts12
-rw-r--r--api/src/util/Attachments.ts12
-rw-r--r--api/src/util/index.ts1
-rw-r--r--util/package-lock.json98
-rw-r--r--util/src/entities/Application.ts4
-rw-r--r--util/src/entities/Attachment.ts13
-rw-r--r--util/src/entities/Ban.ts8
-rw-r--r--util/src/entities/BaseClass.ts48
-rw-r--r--util/src/entities/Channel.ts116
-rw-r--r--util/src/entities/ConnectedAccount.ts4
-rw-r--r--util/src/entities/Emoji.ts4
-rw-r--r--util/src/entities/Guild.ts52
-rw-r--r--util/src/entities/Invite.ts12
-rw-r--r--util/src/entities/Member.ts9
-rw-r--r--util/src/entities/Message.ts22
-rw-r--r--util/src/entities/ReadState.ts8
-rw-r--r--util/src/entities/Recipient.ts8
-rw-r--r--util/src/entities/Relationship.ts8
-rw-r--r--util/src/entities/Role.ts4
-rw-r--r--util/src/entities/Session.ts4
-rw-r--r--util/src/entities/Sticker.ts4
-rw-r--r--util/src/entities/Team.ts4
-rw-r--r--util/src/entities/TeamMember.ts8
-rw-r--r--util/src/entities/User.ts10
-rw-r--r--util/src/entities/VoiceState.ts16
-rw-r--r--util/src/entities/Webhook.ts20
-rw-r--r--util/src/util/Database.ts2
29 files changed, 363 insertions, 171 deletions
diff --git a/api/src/routes/channels/#channel_id/index.ts b/api/src/routes/channels/#channel_id/index.ts
index fde75ec9..61c851e8 100644
--- a/api/src/routes/channels/#channel_id/index.ts
+++ b/api/src/routes/channels/#channel_id/index.ts
@@ -1,6 +1,15 @@
-import { Channel, ChannelDeleteEvent, ChannelPermissionOverwriteType, ChannelType, ChannelUpdateEvent, emitEvent, Recipient } from "@fosscord/util";
+import {
+	Channel,
+	ChannelDeleteEvent,
+	ChannelPermissionOverwriteType,
+	ChannelType,
+	ChannelUpdateEvent,
+	emitEvent,
+	Recipient,
+	handleFile
+} from "@fosscord/util";
 import { Request, Response, Router } from "express";
-import { handleFile, route } from "@fosscord/api";
+import { route } from "@fosscord/api";
 
 const router: Router = Router();
 // TODO: delete channel
@@ -20,15 +29,14 @@ router.delete("/", route({ permission: "MANAGE_CHANNELS" }), async (req: Request
 	const channel = await Channel.findOneOrFail({ where: { id: channel_id }, relations: ["recipients"] });
 
 	if (channel.type === ChannelType.DM) {
-		const recipient = await Recipient.findOneOrFail({ where: { channel_id: channel_id, user_id: req.user_id } })
-		recipient.closed = true
+		const recipient = await Recipient.findOneOrFail({ where: { channel_id: channel_id, user_id: req.user_id } });
+		recipient.closed = true;
 		await Promise.all([
 			recipient.save(),
 			emitEvent({ event: "CHANNEL_DELETE", data: channel, user_id: req.user_id } as ChannelDeleteEvent)
 		]);
-
 	} else if (channel.type === ChannelType.GROUP_DM) {
-		await Channel.removeRecipientFromChannel(channel, req.user_id)
+		await Channel.removeRecipientFromChannel(channel, req.user_id);
 	} else {
 		await Promise.all([
 			Channel.delete({ id: channel_id }),
diff --git a/api/src/routes/channels/#channel_id/messages/#message_id/index.ts b/api/src/routes/channels/#channel_id/messages/#message_id/index.ts
index b5220fab..7f7de264 100644
--- a/api/src/routes/channels/#channel_id/messages/#message_id/index.ts
+++ b/api/src/routes/channels/#channel_id/messages/#message_id/index.ts
@@ -3,7 +3,6 @@ import { Router, Response, Request } from "express";
 import { route } from "@fosscord/api";
 import { handleMessage, postHandleMessage } from "@fosscord/api";
 import { MessageCreateSchema } from "../index";
-import { deleteMessageAttachments } from "@fosscord/api/util/Attachments";
 
 const router = Router();
 // TODO: message content/embed string length limit
@@ -34,7 +33,6 @@ router.patch("/", route({ body: "MessageCreateSchema", permission: "SEND_MESSAGE
 	});
 
 	await Promise.all([
-		await deleteMessageAttachments(message_id, new_message.attachments), //This delete all the attachments not in the array
 		new_message!.save(),
 		await emitEvent({
 			event: "MESSAGE_UPDATE",
@@ -60,7 +58,6 @@ router.delete("/", route({}), async (req: Request, res: Response) => {
 		permission.hasThrow("MANAGE_MESSAGES");
 	}
 
-	await deleteMessageAttachments(message_id);
 	await Message.delete({ id: message_id });
 
 	await emitEvent({
diff --git a/api/src/routes/guilds/#guild_id/delete.ts b/api/src/routes/guilds/#guild_id/delete.ts
index 7c3c5530..bd158c56 100644
--- a/api/src/routes/guilds/#guild_id/delete.ts
+++ b/api/src/routes/guilds/#guild_id/delete.ts
@@ -13,15 +13,8 @@ router.post("/", route({}), async (req: Request, res: Response) => {
 	const guild = await Guild.findOneOrFail({ where: { id: guild_id }, select: ["owner_id"] });
 	if (guild.owner_id !== req.user_id) throw new HTTPError("You are not the owner of this guild", 401);
 
-	// do not put everything into promise all, because of "QueryFailedError: SQLITE_CONSTRAINT: FOREIGN KEY constraint failed"
-
-	await Message.delete({ guild_id }); // messages must be deleted before channel
-
 	await Promise.all([
-		Role.delete({ guild_id }),
-		Channel.delete({ guild_id }),
-		Emoji.delete({ guild_id }),
-		Member.delete({ guild_id }),
+		Guild.delete({ id: guild_id }), // this will also delete all guild related data
 		emitEvent({
 			event: "GUILD_DELETE",
 			data: {
@@ -31,9 +24,6 @@ router.post("/", route({}), async (req: Request, res: Response) => {
 		} as GuildDeleteEvent)
 	]);
 
-	await Invite.delete({ guild_id }); // invite must be deleted after channel
-	await Guild.delete({ id: guild_id }); // guild must be deleted after everything else
-
 	return res.sendStatus(204);
 });
 
diff --git a/api/src/util/Attachments.ts b/api/src/util/Attachments.ts
deleted file mode 100644
index addda97f..00000000
--- a/api/src/util/Attachments.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { Attachment } from "@fosscord/util";
-import { deleteFile } from "@fosscord/api";
-import { URL } from "url";
-
-export async function deleteMessageAttachments(messageId: string, keep?: Attachment[]) {
-	let attachments = await Attachment.find({ message_id: messageId });
-	if (keep)
-		attachments = attachments.filter(x => !keep.map(k => k.id).includes(x.id));
-	await Promise.all(attachments.map(a => a.remove()));
-
-	attachments.forEach(a => deleteFile((new URL(a.url)).pathname)); //We don't need to await since this is done on the cdn
-}
diff --git a/api/src/util/index.ts b/api/src/util/index.ts
index 4b1e8e77..3e47ce4e 100644
--- a/api/src/util/index.ts
+++ b/api/src/util/index.ts
@@ -1,5 +1,4 @@
 export * from "./Base64";
-export * from "./cdn";
 export * from "./FieldError";
 export * from "./ipAddress";
 export * from "./Message";
diff --git a/util/package-lock.json b/util/package-lock.json
index e5a62d0f..f4129614 100644
--- a/util/package-lock.json
+++ b/util/package-lock.json
@@ -226,19 +226,19 @@
 			}
 		},
 		"node_modules/@babel/helper-module-transforms": {
-			"version": "7.15.4",
-			"resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.15.4.tgz",
-			"integrity": "sha512-9fHHSGE9zTC++KuXLZcB5FKgvlV83Ox+NLUmQTawovwlJ85+QMhk1CnVk406CQVj97LaWod6KVjl2Sfgw9Aktw==",
+			"version": "7.15.7",
+			"resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.15.7.tgz",
+			"integrity": "sha512-ZNqjjQG/AuFfekFTY+7nY4RgBSklgTu970c7Rj3m/JOhIu5KPBUuTA9AY6zaKcUvk4g6EbDXdBnhi35FAssdSw==",
 			"dev": true,
 			"dependencies": {
 				"@babel/helper-module-imports": "^7.15.4",
 				"@babel/helper-replace-supers": "^7.15.4",
 				"@babel/helper-simple-access": "^7.15.4",
 				"@babel/helper-split-export-declaration": "^7.15.4",
-				"@babel/helper-validator-identifier": "^7.14.9",
+				"@babel/helper-validator-identifier": "^7.15.7",
 				"@babel/template": "^7.15.4",
 				"@babel/traverse": "^7.15.4",
-				"@babel/types": "^7.15.4"
+				"@babel/types": "^7.15.6"
 			},
 			"engines": {
 				"node": ">=6.9.0"
@@ -305,9 +305,9 @@
 			}
 		},
 		"node_modules/@babel/helper-validator-identifier": {
-			"version": "7.14.9",
-			"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.9.tgz",
-			"integrity": "sha512-pQYxPY0UP6IHISRitNe8bsijHex4TWZXi2HwKVsjPiltzlhse2znVcm9Ace510VT1kxIHjGJCZZQBX2gJDbo0g==",
+			"version": "7.15.7",
+			"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz",
+			"integrity": "sha512-K4JvCtQqad9OY2+yTU8w+E82ywk/fe+ELNlt1G8z3bVGlZfn/hOcQQsUhGhW/N+tb3fxK800wLtKOE/aM0m72w==",
 			"dev": true,
 			"engines": {
 				"node": ">=6.9.0"
@@ -422,9 +422,9 @@
 			}
 		},
 		"node_modules/@babel/parser": {
-			"version": "7.15.6",
-			"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.15.6.tgz",
-			"integrity": "sha512-S/TSCcsRuCkmpUuoWijua0Snt+f3ewU/8spLo+4AXJCZfT0bVCzLD5MuOKdrx0mlAptbKzn5AdgEIIKXxXkz9Q==",
+			"version": "7.15.7",
+			"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.15.7.tgz",
+			"integrity": "sha512-rycZXvQ+xS9QyIcJ9HXeDWf1uxqlbVFAUq0Rq0dbc50Zb/+wUe/ehyfzGfm9KZZF0kBejYgxltBXocP+gKdL2g==",
 			"dev": true,
 			"bin": {
 				"parser": "bin/babel-parser.js"
@@ -1204,9 +1204,9 @@
 			}
 		},
 		"node_modules/@types/node": {
-			"version": "14.17.16",
-			"resolved": "https://registry.npmjs.org/@types/node/-/node-14.17.16.tgz",
-			"integrity": "sha512-WiFf2izl01P1CpeY8WqFAeKWwByMueBEkND38EcN8N68qb0aDG3oIS1P5MhAX5kUdr469qRyqsY/MjanLjsFbQ=="
+			"version": "14.17.17",
+			"resolved": "https://registry.npmjs.org/@types/node/-/node-14.17.17.tgz",
+			"integrity": "sha512-niAjcewgEYvSPCZm3OaM9y6YQrL2SEPH9PymtE6fuZAvFiP6ereCcvApGl2jKTq7copTIguX3PBvfP08LN4LvQ=="
 		},
 		"node_modules/@types/node-fetch": {
 			"version": "2.5.12",
@@ -1941,9 +1941,9 @@
 			}
 		},
 		"node_modules/caniuse-lite": {
-			"version": "1.0.30001257",
-			"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001257.tgz",
-			"integrity": "sha512-JN49KplOgHSXpIsVSF+LUyhD8PUp6xPpAXeRrrcBh4KBeP7W864jHn6RvzJgDlrReyeVjMFJL3PLpPvKIxlIHA==",
+			"version": "1.0.30001258",
+			"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001258.tgz",
+			"integrity": "sha512-RBByOG6xWXUp0CR2/WU2amXz3stjKpSl5J1xU49F1n2OxD//uBZO4wCKUiG+QMGf7CHGfDDcqoKriomoGVxTeA==",
 			"dev": true,
 			"funding": {
 				"type": "opencollective",
@@ -2498,9 +2498,9 @@
 			"integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0="
 		},
 		"node_modules/electron-to-chromium": {
-			"version": "1.3.840",
-			"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.840.tgz",
-			"integrity": "sha512-yRoUmTLDJnkIJx23xLY7GbSvnmDCq++NSuxHDQ0jiyDJ9YZBUGJcrdUqm+ZwZFzMbCciVzfem2N2AWiHJcWlbw==",
+			"version": "1.3.843",
+			"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.843.tgz",
+			"integrity": "sha512-OWEwAbzaVd1Lk9MohVw8LxMXFlnYd9oYTYxfX8KS++kLLjDfbovLOcEEXwRhG612dqGQ6+44SZvim0GXuBRiKg==",
 			"dev": true
 		},
 		"node_modules/emittery": {
@@ -6249,13 +6249,12 @@
 			}
 		},
 		"node_modules/stack-utils": {
-			"version": "2.0.4",
-			"resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.4.tgz",
-			"integrity": "sha512-ERg+H//lSSYlZhBIUu+wJnqg30AbyBbpZlIhcshpn7BNzpoRODZgfyr9J+8ERf3ooC6af3u7Lcl01nleau7MrA==",
+			"version": "2.0.5",
+			"resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.5.tgz",
+			"integrity": "sha512-xrQcmYhOsn/1kX+Vraq+7j4oE2j/6BFscZ0etmYg81xuM8Gq0022Pxb8+IqgOFUIaxHs0KaSb7T1+OegiNrNFA==",
 			"dev": true,
 			"dependencies": {
-				"escape-string-regexp": "^2.0.0",
-				"source-map-support": "^0.5.20"
+				"escape-string-regexp": "^2.0.0"
 			},
 			"engines": {
 				"node": ">=10"
@@ -7535,19 +7534,19 @@
 			}
 		},
 		"@babel/helper-module-transforms": {
-			"version": "7.15.4",
-			"resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.15.4.tgz",
-			"integrity": "sha512-9fHHSGE9zTC++KuXLZcB5FKgvlV83Ox+NLUmQTawovwlJ85+QMhk1CnVk406CQVj97LaWod6KVjl2Sfgw9Aktw==",
+			"version": "7.15.7",
+			"resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.15.7.tgz",
+			"integrity": "sha512-ZNqjjQG/AuFfekFTY+7nY4RgBSklgTu970c7Rj3m/JOhIu5KPBUuTA9AY6zaKcUvk4g6EbDXdBnhi35FAssdSw==",
 			"dev": true,
 			"requires": {
 				"@babel/helper-module-imports": "^7.15.4",
 				"@babel/helper-replace-supers": "^7.15.4",
 				"@babel/helper-simple-access": "^7.15.4",
 				"@babel/helper-split-export-declaration": "^7.15.4",
-				"@babel/helper-validator-identifier": "^7.14.9",
+				"@babel/helper-validator-identifier": "^7.15.7",
 				"@babel/template": "^7.15.4",
 				"@babel/traverse": "^7.15.4",
-				"@babel/types": "^7.15.4"
+				"@babel/types": "^7.15.6"
 			}
 		},
 		"@babel/helper-optimise-call-expression": {
@@ -7596,9 +7595,9 @@
 			}
 		},
 		"@babel/helper-validator-identifier": {
-			"version": "7.14.9",
-			"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.14.9.tgz",
-			"integrity": "sha512-pQYxPY0UP6IHISRitNe8bsijHex4TWZXi2HwKVsjPiltzlhse2znVcm9Ace510VT1kxIHjGJCZZQBX2gJDbo0g==",
+			"version": "7.15.7",
+			"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.15.7.tgz",
+			"integrity": "sha512-K4JvCtQqad9OY2+yTU8w+E82ywk/fe+ELNlt1G8z3bVGlZfn/hOcQQsUhGhW/N+tb3fxK800wLtKOE/aM0m72w==",
 			"dev": true
 		},
 		"@babel/helper-validator-option": {
@@ -7688,9 +7687,9 @@
 			}
 		},
 		"@babel/parser": {
-			"version": "7.15.6",
-			"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.15.6.tgz",
-			"integrity": "sha512-S/TSCcsRuCkmpUuoWijua0Snt+f3ewU/8spLo+4AXJCZfT0bVCzLD5MuOKdrx0mlAptbKzn5AdgEIIKXxXkz9Q==",
+			"version": "7.15.7",
+			"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.15.7.tgz",
+			"integrity": "sha512-rycZXvQ+xS9QyIcJ9HXeDWf1uxqlbVFAUq0Rq0dbc50Zb/+wUe/ehyfzGfm9KZZF0kBejYgxltBXocP+gKdL2g==",
 			"dev": true
 		},
 		"@babel/plugin-syntax-async-generators": {
@@ -8336,9 +8335,9 @@
 			}
 		},
 		"@types/node": {
-			"version": "14.17.16",
-			"resolved": "https://registry.npmjs.org/@types/node/-/node-14.17.16.tgz",
-			"integrity": "sha512-WiFf2izl01P1CpeY8WqFAeKWwByMueBEkND38EcN8N68qb0aDG3oIS1P5MhAX5kUdr469qRyqsY/MjanLjsFbQ=="
+			"version": "14.17.17",
+			"resolved": "https://registry.npmjs.org/@types/node/-/node-14.17.17.tgz",
+			"integrity": "sha512-niAjcewgEYvSPCZm3OaM9y6YQrL2SEPH9PymtE6fuZAvFiP6ereCcvApGl2jKTq7copTIguX3PBvfP08LN4LvQ=="
 		},
 		"@types/node-fetch": {
 			"version": "2.5.12",
@@ -8945,9 +8944,9 @@
 			"dev": true
 		},
 		"caniuse-lite": {
-			"version": "1.0.30001257",
-			"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001257.tgz",
-			"integrity": "sha512-JN49KplOgHSXpIsVSF+LUyhD8PUp6xPpAXeRrrcBh4KBeP7W864jHn6RvzJgDlrReyeVjMFJL3PLpPvKIxlIHA==",
+			"version": "1.0.30001258",
+			"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001258.tgz",
+			"integrity": "sha512-RBByOG6xWXUp0CR2/WU2amXz3stjKpSl5J1xU49F1n2OxD//uBZO4wCKUiG+QMGf7CHGfDDcqoKriomoGVxTeA==",
 			"dev": true
 		},
 		"caseless": {
@@ -9405,9 +9404,9 @@
 			"integrity": "sha1-WQxhFWsK4vTwJVcyoViyZrxWsh0="
 		},
 		"electron-to-chromium": {
-			"version": "1.3.840",
-			"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.840.tgz",
-			"integrity": "sha512-yRoUmTLDJnkIJx23xLY7GbSvnmDCq++NSuxHDQ0jiyDJ9YZBUGJcrdUqm+ZwZFzMbCciVzfem2N2AWiHJcWlbw==",
+			"version": "1.3.843",
+			"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.3.843.tgz",
+			"integrity": "sha512-OWEwAbzaVd1Lk9MohVw8LxMXFlnYd9oYTYxfX8KS++kLLjDfbovLOcEEXwRhG612dqGQ6+44SZvim0GXuBRiKg==",
 			"dev": true
 		},
 		"emittery": {
@@ -12300,13 +12299,12 @@
 			}
 		},
 		"stack-utils": {
-			"version": "2.0.4",
-			"resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.4.tgz",
-			"integrity": "sha512-ERg+H//lSSYlZhBIUu+wJnqg30AbyBbpZlIhcshpn7BNzpoRODZgfyr9J+8ERf3ooC6af3u7Lcl01nleau7MrA==",
+			"version": "2.0.5",
+			"resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.5.tgz",
+			"integrity": "sha512-xrQcmYhOsn/1kX+Vraq+7j4oE2j/6BFscZ0etmYg81xuM8Gq0022Pxb8+IqgOFUIaxHs0KaSb7T1+OegiNrNFA==",
 			"dev": true,
 			"requires": {
-				"escape-string-regexp": "^2.0.0",
-				"source-map-support": "^0.5.20"
+				"escape-string-regexp": "^2.0.0"
 			}
 		},
 		"statuses": {
diff --git a/util/src/entities/Application.ts b/util/src/entities/Application.ts
index 2092cd4e..fab3d93f 100644
--- a/util/src/entities/Application.ts
+++ b/util/src/entities/Application.ts
@@ -41,7 +41,9 @@ export class Application extends BaseClass {
 	verify_key: string;
 
 	@JoinColumn({ name: "team_id" })
-	@ManyToOne(() => Team)
+	@ManyToOne(() => Team, {
+		onDelete: "CASCADE",
+	})
 	team?: Team;
 
 	@JoinColumn({ name: "guild_id" })
diff --git a/util/src/entities/Attachment.ts b/util/src/entities/Attachment.ts
index ca893400..7b4b17eb 100644
--- a/util/src/entities/Attachment.ts
+++ b/util/src/entities/Attachment.ts
@@ -1,4 +1,6 @@
-import { Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm";
+import { BeforeRemove, Column, Entity, JoinColumn, ManyToOne, RelationId } from "typeorm";
+import { URL } from "url";
+import { deleteFile } from "../util/cdn";
 import { BaseClass } from "./BaseClass";
 
 @Entity("attachments")
@@ -29,6 +31,13 @@ export class Attachment extends BaseClass {
 	message_id: string;
 
 	@JoinColumn({ name: "message_id" })
-	@ManyToOne(() => require("./Message").Message, (message: import("./Message").Message) => message.attachments)
+	@ManyToOne(() => require("./Message").Message, (message: import("./Message").Message) => message.attachments, {
+		onDelete: "CASCADE",
+	})
 	message: import("./Message").Message;
+
+	@BeforeRemove()
+	onDelete() {
+		return deleteFile(new URL(this.url).pathname);
+	}
 }
diff --git a/util/src/entities/Ban.ts b/util/src/entities/Ban.ts
index e8a6d648..9504bd8e 100644
--- a/util/src/entities/Ban.ts
+++ b/util/src/entities/Ban.ts
@@ -10,7 +10,9 @@ export class Ban extends BaseClass {
 	user_id: string;
 
 	@JoinColumn({ name: "user_id" })
-	@ManyToOne(() => User)
+	@ManyToOne(() => User, {
+		onDelete: "CASCADE",
+	})
 	user: User;
 
 	@Column({ nullable: true })
@@ -18,7 +20,9 @@ export class Ban extends BaseClass {
 	guild_id: string;
 
 	@JoinColumn({ name: "guild_id" })
-	@ManyToOne(() => Guild)
+	@ManyToOne(() => Guild, {
+		onDelete: "CASCADE",
+	})
 	guild: Guild;
 
 	@Column({ nullable: true })
diff --git a/util/src/entities/BaseClass.ts b/util/src/entities/BaseClass.ts
index 9b2ce058..d18757f2 100644
--- a/util/src/entities/BaseClass.ts
+++ b/util/src/entities/BaseClass.ts
@@ -1,5 +1,15 @@
 import "reflect-metadata";
-import { BaseEntity, BeforeInsert, BeforeUpdate, EntityMetadata, FindConditions, PrimaryColumn } from "typeorm";
+import {
+	BaseEntity,
+	BeforeInsert,
+	BeforeUpdate,
+	EntityMetadata,
+	FindConditions,
+	getConnection,
+	getManager,
+	PrimaryColumn,
+	RemoveOptions,
+} from "typeorm";
 import { Snowflake } from "../util/Snowflake";
 import "missing-native-js-functions";
 
@@ -69,6 +79,42 @@ export class BaseClassWithoutId extends BaseEntity {
 		const repository = this.getRepository();
 		return repository.decrement(conditions, propertyPath, value);
 	}
+
+	// static async delete<T>(criteria: FindConditions<T>, options?: RemoveOptions) {
+	// 	if (!criteria) throw new Error("You need to specify delete criteria");
+
+	// 	const repository = this.getRepository();
+	// 	const promises = repository.metadata.relations.map(async (x) => {
+	// 		if (x.orphanedRowAction !== "delete") return;
+
+	// 		const foreignKey =
+	// 			x.foreignKeys.find((key) => key.entityMetadata === repository.metadata) ||
+	// 			x.inverseRelation?.foreignKeys[0]; // find foreign key for this entity
+	// 		if (!foreignKey) {
+	// 			throw new Error(
+	// 				`Foreign key not found for entity ${repository.metadata.name} in relation ${x.propertyName}`
+	// 			);
+	// 		}
+	// 		const id = (criteria as any)[foreignKey.referencedColumnNames[0]];
+	// 		if (!id) throw new Error("id missing in criteria options " + foreignKey.referencedColumnNames);
+
+	// 		if (x.relationType === "many-to-many") {
+	// 			return getConnection()
+	// 				.createQueryBuilder()
+	// 				.relation(this, x.propertyName)
+	// 				.of(id)
+	// 				.remove({ [foreignKey.columnNames[0]]: id });
+	// 		} else if (
+	// 			x.relationType === "one-to-one" ||
+	// 			x.relationType === "many-to-one" ||
+	// 			x.relationType === "one-to-many"
+	// 		) {
+	// 			return (x.inverseEntityMetadata.target as any).delete({ [foreignKey.columnNames[0]]: id });
+	// 		}
+	// 	});
+	// 	await Promise.all(promises);
+	// 	return super.delete(criteria, options);
+	// }
 }
 
 export class BaseClass extends BaseClassWithoutId {
diff --git a/util/src/entities/Channel.ts b/util/src/entities/Channel.ts
index ea632778..ece82bd0 100644
--- a/util/src/entities/Channel.ts
+++ b/util/src/entities/Channel.ts
@@ -6,8 +6,12 @@ import { HTTPError } from "lambert-server";
 import { containsAll, emitEvent, getPermission, Snowflake, trimSpecial } from "../util";
 import { ChannelCreateEvent, ChannelRecipientRemoveEvent } from "../interfaces";
 import { Recipient } from "./Recipient";
-import { DmChannelDTO } from "../dtos";
 import { Message } from "./Message";
+import { ReadState } from "./ReadState";
+import { Invite } from "./Invite";
+import { VoiceState } from "./VoiceState";
+import { Webhook } from "./Webhook";
+import { DmChannelDTO } from "../dtos";
 
 export enum ChannelType {
 	GUILD_TEXT = 0, // a text channel within a server
@@ -32,13 +36,16 @@ export class Channel extends BaseClass {
 	@Column({ nullable: true })
 	name?: string;
 
-	@Column({ type: 'text', nullable: true })
+	@Column({ type: "text", nullable: true })
 	icon?: string | null;
 
 	@Column({ type: "simple-enum", enum: ChannelType })
 	type: ChannelType;
 
-	@OneToMany(() => Recipient, (recipient: Recipient) => recipient.channel, { cascade: true })
+	@OneToMany(() => Recipient, (recipient: Recipient) => recipient.channel, {
+		cascade: true,
+		orphanedRowAction: "delete",
+	})
 	recipients?: Recipient[];
 
 	@Column({ nullable: true })
@@ -49,7 +56,9 @@ export class Channel extends BaseClass {
 	guild_id?: string;
 
 	@JoinColumn({ name: "guild_id" })
-	@ManyToOne(() => Guild)
+	@ManyToOne(() => Guild, {
+		onDelete: "CASCADE",
+	})
 	guild: Guild;
 
 	@Column({ nullable: true })
@@ -99,6 +108,37 @@ export class Channel extends BaseClass {
 	@Column({ nullable: true })
 	topic?: string;
 
+	@OneToMany(() => Invite, (invite: Invite) => invite.channel, {
+		cascade: true,
+		orphanedRowAction: "delete",
+	})
+	invites?: Invite[];
+
+	@OneToMany(() => Message, (message: Message) => message.channel, {
+		cascade: true,
+		orphanedRowAction: "delete",
+	})
+	messages?: Message[];
+
+	@OneToMany(() => VoiceState, (voice_state: VoiceState) => voice_state.channel, {
+		cascade: true,
+		orphanedRowAction: "delete",
+	})
+	voice_states?: VoiceState[];
+
+	@OneToMany(() => ReadState, (read_state: ReadState) => read_state.channel, {
+		cascade: true,
+		orphanedRowAction: "delete",
+	})
+	read_states?: ReadState[];
+
+	@OneToMany(() => Webhook, (webhook: Webhook) => webhook.channel, {
+		cascade: true,
+		orphanedRowAction: "delete",
+	})
+	webhooks?: Webhook[];
+
+	// TODO: DM channel
 	static async createChannel(
 		channel: Partial<Channel>,
 		user_id: string = "0",
@@ -151,10 +191,10 @@ export class Channel extends BaseClass {
 			new Channel(channel).save(),
 			!opts?.skipEventEmit
 				? emitEvent({
-					event: "CHANNEL_CREATE",
-					data: channel,
-					guild_id: channel.guild_id,
-				} as ChannelCreateEvent)
+						event: "CHANNEL_CREATE",
+						data: channel,
+						guild_id: channel.guild_id,
+				  } as ChannelCreateEvent)
 				: Promise.resolve(),
 		]);
 
@@ -174,17 +214,20 @@ export class Channel extends BaseClass {
 
 		let channel = null;
 
-		const channelRecipients = [...recipients, creator_user_id]
+		const channelRecipients = [...recipients, creator_user_id];
 
-		const userRecipients = await Recipient.find({ where: { user_id: creator_user_id }, relations: ["channel", "channel.recipients"] })
+		const userRecipients = await Recipient.find({
+			where: { user_id: creator_user_id },
+			relations: ["channel", "channel.recipients"],
+		});
 
 		for (let ur of userRecipients) {
-			let re = ur.channel.recipients!.map(r => r.user_id)
+			let re = ur.channel.recipients!.map((r) => r.user_id);
 			if (re.length === channelRecipients.length) {
 				if (containsAll(re, channelRecipients)) {
 					if (channel == null) {
-						channel = ur.channel
-						await ur.assign({ closed: false }).save()
+						channel = ur.channel;
+						await ur.assign({ closed: false }).save();
 					}
 				}
 			}
@@ -196,80 +239,83 @@ export class Channel extends BaseClass {
 			channel = await new Channel({
 				name,
 				type,
-				owner_id: (type === ChannelType.DM ? undefined : creator_user_id),
+				owner_id: type === ChannelType.DM ? undefined : creator_user_id,
 				created_at: new Date(),
 				last_message_id: null,
-				recipients: channelRecipients.map((x) => new Recipient({ user_id: x, closed: !(type === ChannelType.GROUP_DM || x === creator_user_id) })),
+				recipients: channelRecipients.map(
+					(x) =>
+						new Recipient({ user_id: x, closed: !(type === ChannelType.GROUP_DM || x === creator_user_id) })
+				),
 			}).save();
 		}
 
-
-		const channel_dto = await DmChannelDTO.from(channel)
+		const channel_dto = await DmChannelDTO.from(channel);
 
 		if (type === ChannelType.GROUP_DM) {
-
 			for (let recipient of channel.recipients!) {
 				await emitEvent({
 					event: "CHANNEL_CREATE",
 					data: channel_dto.excludedRecipients([recipient.user_id]),
-					user_id: recipient.user_id
-				})
+					user_id: recipient.user_id,
+				});
 			}
 		} else {
 			await emitEvent({ event: "CHANNEL_CREATE", data: channel_dto, user_id: creator_user_id });
 		}
 
-		return channel_dto.excludedRecipients([creator_user_id])
+		return channel_dto.excludedRecipients([creator_user_id]);
 	}
 
 	static async removeRecipientFromChannel(channel: Channel, user_id: string) {
-		await Recipient.delete({ channel_id: channel.id, user_id: user_id })
-		channel.recipients = channel.recipients?.filter(r => r.user_id !== user_id)
+		await Recipient.delete({ channel_id: channel.id, user_id: user_id });
+		channel.recipients = channel.recipients?.filter((r) => r.user_id !== user_id);
 
 		if (channel.recipients?.length === 0) {
 			await Channel.deleteChannel(channel);
 			await emitEvent({
 				event: "CHANNEL_DELETE",
 				data: await DmChannelDTO.from(channel, [user_id]),
-				user_id: user_id
+				user_id: user_id,
 			});
-			return
+			return;
 		}
 
 		await emitEvent({
 			event: "CHANNEL_DELETE",
 			data: await DmChannelDTO.from(channel, [user_id]),
-			user_id: user_id
+			user_id: user_id,
 		});
 
 		//If the owner leave we make the first recipient in the list the new owner
 		if (channel.owner_id === user_id) {
-			channel.owner_id = channel.recipients!.find(r => r.user_id !== user_id)!.user_id //Is there a criteria to choose the new owner?
+			channel.owner_id = channel.recipients!.find((r) => r.user_id !== user_id)!.user_id; //Is there a criteria to choose the new owner?
 			await emitEvent({
 				event: "CHANNEL_UPDATE",
 				data: await DmChannelDTO.from(channel, [user_id]),
-				channel_id: channel.id
+				channel_id: channel.id,
 			});
 		}
 
-		await channel.save()
+		await channel.save();
 
 		await emitEvent({
-			event: "CHANNEL_RECIPIENT_REMOVE", data: {
+			event: "CHANNEL_RECIPIENT_REMOVE",
+			data: {
 				channel_id: channel.id,
-				user: await User.findOneOrFail({ where: { id: user_id }, select: PublicUserProjection })
-			}, channel_id: channel.id
+				user: await User.findOneOrFail({ where: { id: user_id }, select: PublicUserProjection }),
+			},
+			channel_id: channel.id,
 		} as ChannelRecipientRemoveEvent);
 	}
 
 	static async deleteChannel(channel: Channel) {
-		await Message.delete({ channel_id: channel.id }) //TODO we should also delete the attachments from the cdn but to do that we need to move cdn.ts in util
+		await Message.delete({ channel_id: channel.id }); //TODO we should also delete the attachments from the cdn but to do that we need to move cdn.ts in util
 		//TODO before deleting the channel we should check and delete other relations
-		await Channel.delete({ id: channel.id })
+		await Channel.delete({ id: channel.id });
 	}
 
 	isDm() {
-		return this.type === ChannelType.DM || this.type === ChannelType.GROUP_DM
+		return this.type === ChannelType.DM || this.type === ChannelType.GROUP_DM;
 	}
 }
 
diff --git a/util/src/entities/ConnectedAccount.ts b/util/src/entities/ConnectedAccount.ts
index 59a8f423..b8aa2889 100644
--- a/util/src/entities/ConnectedAccount.ts
+++ b/util/src/entities/ConnectedAccount.ts
@@ -11,7 +11,9 @@ export class ConnectedAccount extends BaseClass {
 	user_id: string;
 
 	@JoinColumn({ name: "user_id" })
-	@ManyToOne(() => User)
+	@ManyToOne(() => User, {
+		onDelete: "CASCADE",
+	})
 	user: User;
 
 	@Column({ select: false })
diff --git a/util/src/entities/Emoji.ts b/util/src/entities/Emoji.ts
index 181aff2c..a252d9f4 100644
--- a/util/src/entities/Emoji.ts
+++ b/util/src/entities/Emoji.ts
@@ -15,7 +15,9 @@ export class Emoji extends BaseClass {
 	guild_id: string;
 
 	@JoinColumn({ name: "guild_id" })
-	@ManyToOne(() => Guild)
+	@ManyToOne(() => Guild, {
+		onDelete: "CASCADE",
+	})
 	guild: Guild;
 
 	@Column()
diff --git a/util/src/entities/Guild.ts b/util/src/entities/Guild.ts
index 7b5d2908..e107937d 100644
--- a/util/src/entities/Guild.ts
+++ b/util/src/entities/Guild.ts
@@ -81,7 +81,10 @@ export class Guild extends BaseClass {
 	// application?: string;
 
 	@JoinColumn({ name: "ban_ids" })
-	@OneToMany(() => Ban, (ban: Ban) => ban.guild)
+	@OneToMany(() => Ban, (ban: Ban) => ban.guild, {
+		cascade: true,
+		orphanedRowAction: "delete",
+	})
 	bans: Ban[];
 
 	@Column({ nullable: true })
@@ -124,15 +127,26 @@ export class Guild extends BaseClass {
 	@Column({ nullable: true })
 	presence_count?: number; // users online
 
-	@OneToMany(() => Member, (member: Member) => member.guild)
+	@OneToMany(() => Member, (member: Member) => member.guild, {
+		cascade: true,
+		orphanedRowAction: "delete",
+		onDelete: "CASCADE",
+	})
 	members: Member[];
 
 	@JoinColumn({ name: "role_ids" })
-	@OneToMany(() => Role, (role: Role) => role.guild)
+	@OneToMany(() => Role, (role: Role) => role.guild, {
+		cascade: true,
+		orphanedRowAction: "delete",
+		onDelete: "CASCADE",
+	})
 	roles: Role[];
 
 	@JoinColumn({ name: "channel_ids" })
-	@OneToMany(() => Channel, (channel: Channel) => channel.guild)
+	@OneToMany(() => Channel, (channel: Channel) => channel.guild, {
+		cascade: true,
+		orphanedRowAction: "delete",
+	})
 	channels: Channel[];
 
 	@Column({ nullable: true })
@@ -144,23 +158,43 @@ export class Guild extends BaseClass {
 	template: Template;
 
 	@JoinColumn({ name: "emoji_ids" })
-	@OneToMany(() => Emoji, (emoji: Emoji) => emoji.guild)
+	@OneToMany(() => Emoji, (emoji: Emoji) => emoji.guild, {
+		cascade: true,
+		orphanedRowAction: "delete",
+		onDelete: "CASCADE",
+	})
 	emojis: Emoji[];
 
 	@JoinColumn({ name: "sticker_ids" })
-	@OneToMany(() => Sticker, (sticker: Sticker) => sticker.guild)
+	@OneToMany(() => Sticker, (sticker: Sticker) => sticker.guild, {
+		cascade: true,
+		orphanedRowAction: "delete",
+		onDelete: "CASCADE",
+	})
 	stickers: Sticker[];
 
 	@JoinColumn({ name: "invite_ids" })
-	@OneToMany(() => Invite, (invite: Invite) => invite.guild)
+	@OneToMany(() => Invite, (invite: Invite) => invite.guild, {
+		cascade: true,
+		orphanedRowAction: "delete",
+		onDelete: "CASCADE",
+	})
 	invites: Invite[];
 
 	@JoinColumn({ name: "voice_state_ids" })
-	@OneToMany(() => VoiceState, (voicestate: VoiceState) => voicestate.guild)
+	@OneToMany(() => VoiceState, (voicestate: VoiceState) => voicestate.guild, {
+		cascade: true,
+		orphanedRowAction: "delete",
+		onDelete: "CASCADE",
+	})
 	voice_states: VoiceState[];
 
 	@JoinColumn({ name: "webhook_ids" })
-	@OneToMany(() => Webhook, (webhook: Webhook) => webhook.guild)
+	@OneToMany(() => Webhook, (webhook: Webhook) => webhook.guild, {
+		cascade: true,
+		orphanedRowAction: "delete",
+		onDelete: "CASCADE",
+	})
 	webhooks: Webhook[];
 
 	@Column({ nullable: true })
diff --git a/util/src/entities/Invite.ts b/util/src/entities/Invite.ts
index 1396004e..78545b02 100644
--- a/util/src/entities/Invite.ts
+++ b/util/src/entities/Invite.ts
@@ -35,7 +35,9 @@ export class Invite extends BaseClass {
 	guild_id: string;
 
 	@JoinColumn({ name: "guild_id" })
-	@ManyToOne(() => Guild)
+	@ManyToOne(() => Guild, {
+		onDelete: "CASCADE",
+	})
 	guild: Guild;
 
 	@Column({ nullable: true })
@@ -43,7 +45,9 @@ export class Invite extends BaseClass {
 	channel_id: string;
 
 	@JoinColumn({ name: "channel_id" })
-	@ManyToOne(() => Channel)
+	@ManyToOne(() => Channel, {
+		onDelete: "CASCADE",
+	})
 	channel: Channel;
 
 	@Column({ nullable: true })
@@ -59,7 +63,9 @@ export class Invite extends BaseClass {
 	target_user_id: string;
 
 	@JoinColumn({ name: "target_user_id" })
-	@ManyToOne(() => User)
+	@ManyToOne(() => User, {
+		onDelete: "CASCADE",
+	})
 	target_user?: string; // could be used for "User specific invites" https://github.com/fosscord/fosscord/issues/62
 
 	@Column({ nullable: true })
diff --git a/util/src/entities/Member.ts b/util/src/entities/Member.ts
index 66f5d9a1..feb9c069 100644
--- a/util/src/entities/Member.ts
+++ b/util/src/entities/Member.ts
@@ -39,7 +39,9 @@ export class Member extends BaseClassWithoutId {
 	id: string;
 
 	@JoinColumn({ name: "id" })
-	@ManyToOne(() => User)
+	@ManyToOne(() => User, {
+		onDelete: "CASCADE",
+	})
 	user: User;
 
 	@Column()
@@ -47,7 +49,9 @@ export class Member extends BaseClassWithoutId {
 	guild_id: string;
 
 	@JoinColumn({ name: "guild_id" })
-	@ManyToOne(() => Guild)
+	@ManyToOne(() => Guild, {
+		onDelete: "CASCADE",
+	})
 	guild: Guild;
 
 	@Column({ nullable: true })
@@ -55,7 +59,6 @@ export class Member extends BaseClassWithoutId {
 
 	@JoinTable({
 		name: "member_roles",
-
 		joinColumn: { name: "index", referencedColumnName: "index" },
 		inverseJoinColumn: {
 			name: "role_id",
diff --git a/util/src/entities/Message.ts b/util/src/entities/Message.ts
index 506db71a..c4901693 100644
--- a/util/src/entities/Message.ts
+++ b/util/src/entities/Message.ts
@@ -8,12 +8,14 @@ import {
 	Column,
 	CreateDateColumn,
 	Entity,
+	FindConditions,
 	JoinColumn,
 	JoinTable,
 	ManyToMany,
 	ManyToOne,
 	OneToMany,
 	RelationId,
+	RemoveOptions,
 	UpdateDateColumn,
 } from "typeorm";
 import { BaseClass } from "./BaseClass";
@@ -52,7 +54,9 @@ export class Message extends BaseClass {
 	channel_id: string;
 
 	@JoinColumn({ name: "channel_id" })
-	@ManyToOne(() => Channel)
+	@ManyToOne(() => Channel, {
+		onDelete: "CASCADE",
+	})
 	channel: Channel;
 
 	@Column({ nullable: true })
@@ -60,7 +64,9 @@ export class Message extends BaseClass {
 	guild_id?: string;
 
 	@JoinColumn({ name: "guild_id" })
-	@ManyToOne(() => Guild)
+	@ManyToOne(() => Guild, {
+		onDelete: "CASCADE",
+	})
 	guild?: Guild;
 
 	@Column({ nullable: true })
@@ -68,7 +74,9 @@ export class Message extends BaseClass {
 	author_id: string;
 
 	@JoinColumn({ name: "author_id", referencedColumnName: "id" })
-	@ManyToOne(() => User)
+	@ManyToOne(() => User, {
+		onDelete: "CASCADE",
+	})
 	author?: User;
 
 	@Column({ nullable: true })
@@ -112,7 +120,7 @@ export class Message extends BaseClass {
 	mention_everyone?: boolean;
 
 	@JoinTable({ name: "message_user_mentions" })
-	@ManyToMany(() => User)
+	@ManyToMany(() => User, { orphanedRowAction: "delete", onDelete: "CASCADE", cascade: true })
 	mentions: User[];
 
 	@JoinTable({ name: "message_role_mentions" })
@@ -127,8 +135,10 @@ export class Message extends BaseClass {
 	@ManyToMany(() => Sticker)
 	sticker_items?: Sticker[];
 
-	@JoinColumn({ name: "attachment_ids" })
-	@OneToMany(() => Attachment, (attachment: Attachment) => attachment.message, { cascade: true })
+	@OneToMany(() => Attachment, (attachment: Attachment) => attachment.message, {
+		cascade: true,
+		orphanedRowAction: "delete",
+	})
 	attachments?: Attachment[];
 
 	@Column({ type: "simple-json" })
diff --git a/util/src/entities/ReadState.ts b/util/src/entities/ReadState.ts
index 8dd05b21..68e867a0 100644
--- a/util/src/entities/ReadState.ts
+++ b/util/src/entities/ReadState.ts
@@ -15,7 +15,9 @@ export class ReadState extends BaseClass {
 	channel_id: string;
 
 	@JoinColumn({ name: "channel_id" })
-	@ManyToOne(() => Channel)
+	@ManyToOne(() => Channel, {
+		onDelete: "CASCADE",
+	})
 	channel: Channel;
 
 	@Column({ nullable: true })
@@ -23,7 +25,9 @@ export class ReadState extends BaseClass {
 	user_id: string;
 
 	@JoinColumn({ name: "user_id" })
-	@ManyToOne(() => User)
+	@ManyToOne(() => User, {
+		onDelete: "CASCADE",
+	})
 	user: User;
 
 	@Column({ nullable: true })
diff --git a/util/src/entities/Recipient.ts b/util/src/entities/Recipient.ts
index bb280588..a945f938 100644
--- a/util/src/entities/Recipient.ts
+++ b/util/src/entities/Recipient.ts
@@ -8,7 +8,9 @@ export class Recipient extends BaseClass {
 	channel_id: string;
 
 	@JoinColumn({ name: "channel_id" })
-	@ManyToOne(() => require("./Channel").Channel)
+	@ManyToOne(() => require("./Channel").Channel, {
+		onDelete: "CASCADE",
+	})
 	channel: import("./Channel").Channel;
 
 	@Column()
@@ -16,7 +18,9 @@ export class Recipient extends BaseClass {
 	user_id: string;
 
 	@JoinColumn({ name: "user_id" })
-	@ManyToOne(() => require("./User").User)
+	@ManyToOne(() => require("./User").User, {
+		onDelete: "CASCADE",
+	})
 	user: import("./User").User;
 
 	@Column({ default: false })
diff --git a/util/src/entities/Relationship.ts b/util/src/entities/Relationship.ts
index 61b3ac82..e016b36b 100644
--- a/util/src/entities/Relationship.ts
+++ b/util/src/entities/Relationship.ts
@@ -17,7 +17,9 @@ export class Relationship extends BaseClass {
 	from_id: string;
 
 	@JoinColumn({ name: "from_id" })
-	@ManyToOne(() => User)
+	@ManyToOne(() => User, {
+		onDelete: "CASCADE",
+	})
 	from: User;
 
 	@Column({})
@@ -25,7 +27,9 @@ export class Relationship extends BaseClass {
 	to_id: string;
 
 	@JoinColumn({ name: "to_id" })
-	@ManyToOne(() => User)
+	@ManyToOne(() => User, {
+		onDelete: "CASCADE",
+	})
 	to: User;
 
 	@Column({ nullable: true })
diff --git a/util/src/entities/Role.ts b/util/src/entities/Role.ts
index 33c8d272..9fca99a5 100644
--- a/util/src/entities/Role.ts
+++ b/util/src/entities/Role.ts
@@ -10,7 +10,9 @@ export class Role extends BaseClass {
 	guild_id: string;
 
 	@JoinColumn({ name: "guild_id" })
-	@ManyToOne(() => Guild)
+	@ManyToOne(() => Guild, {
+		onDelete: "CASCADE",
+	})
 	guild: Guild;
 
 	@Column()
diff --git a/util/src/entities/Session.ts b/util/src/entities/Session.ts
index d42a8f98..7cc325f5 100644
--- a/util/src/entities/Session.ts
+++ b/util/src/entities/Session.ts
@@ -11,7 +11,9 @@ export class Session extends BaseClass {
 	user_id: string;
 
 	@JoinColumn({ name: "user_id" })
-	@ManyToOne(() => User)
+	@ManyToOne(() => User, {
+		onDelete: "CASCADE",
+	})
 	user: User;
 
 	//TODO check, should be 32 char long hex string
diff --git a/util/src/entities/Sticker.ts b/util/src/entities/Sticker.ts
index 7730a86a..ab224d1d 100644
--- a/util/src/entities/Sticker.ts
+++ b/util/src/entities/Sticker.ts
@@ -31,7 +31,9 @@ export class Sticker extends BaseClass {
 	guild_id?: string;
 
 	@JoinColumn({ name: "guild_id" })
-	@ManyToOne(() => Guild)
+	@ManyToOne(() => Guild, {
+		onDelete: "CASCADE",
+	})
 	guild?: Guild;
 
 	@Column({ type: "simple-enum", enum: StickerType })
diff --git a/util/src/entities/Team.ts b/util/src/entities/Team.ts
index beb8bf68..22140b7f 100644
--- a/util/src/entities/Team.ts
+++ b/util/src/entities/Team.ts
@@ -9,7 +9,9 @@ export class Team extends BaseClass {
 	icon?: string;
 
 	@JoinColumn({ name: "member_ids" })
-	@OneToMany(() => TeamMember, (member: TeamMember) => member.team)
+	@OneToMany(() => TeamMember, (member: TeamMember) => member.team, {
+		orphanedRowAction: "delete",
+	})
 	members: TeamMember[];
 
 	@Column()
diff --git a/util/src/entities/TeamMember.ts b/util/src/entities/TeamMember.ts
index 6b184d08..bdfdccf0 100644
--- a/util/src/entities/TeamMember.ts
+++ b/util/src/entities/TeamMember.ts
@@ -20,7 +20,9 @@ export class TeamMember extends BaseClass {
 	team_id: string;
 
 	@JoinColumn({ name: "team_id" })
-	@ManyToOne(() => require("./Team").Team, (team: import("./Team").Team) => team.members)
+	@ManyToOne(() => require("./Team").Team, (team: import("./Team").Team) => team.members, {
+		onDelete: "CASCADE",
+	})
 	team: import("./Team").Team;
 
 	@Column({ nullable: true })
@@ -28,6 +30,8 @@ export class TeamMember extends BaseClass {
 	user_id: string;
 
 	@JoinColumn({ name: "user_id" })
-	@ManyToOne(() => User)
+	@ManyToOne(() => User, {
+		onDelete: "CASCADE",
+	})
 	user: User;
 }
diff --git a/util/src/entities/User.ts b/util/src/entities/User.ts
index cef88777..4c86b2d8 100644
--- a/util/src/entities/User.ts
+++ b/util/src/entities/User.ts
@@ -127,11 +127,17 @@ export class User extends BaseClass {
 	public_flags: number;
 
 	@JoinColumn({ name: "relationship_ids" })
-	@OneToMany(() => Relationship, (relationship: Relationship) => relationship.from)
+	@OneToMany(() => Relationship, (relationship: Relationship) => relationship.from, {
+		cascade: true,
+		orphanedRowAction: "delete",
+	})
 	relationships: Relationship[];
 
 	@JoinColumn({ name: "connected_account_ids" })
-	@OneToMany(() => ConnectedAccount, (account: ConnectedAccount) => account.user)
+	@OneToMany(() => ConnectedAccount, (account: ConnectedAccount) => account.user, {
+		cascade: true,
+		orphanedRowAction: "delete",
+	})
 	connected_accounts: ConnectedAccount[];
 
 	@Column({ type: "simple-json", select: false })
diff --git a/util/src/entities/VoiceState.ts b/util/src/entities/VoiceState.ts
index 56eb244e..75748a01 100644
--- a/util/src/entities/VoiceState.ts
+++ b/util/src/entities/VoiceState.ts
@@ -13,7 +13,9 @@ export class VoiceState extends BaseClass {
 	guild_id: string;
 
 	@JoinColumn({ name: "guild_id" })
-	@ManyToOne(() => Guild)
+	@ManyToOne(() => Guild, {
+		onDelete: "CASCADE",
+	})
 	guild?: Guild;
 
 	@Column({ nullable: true })
@@ -21,7 +23,9 @@ export class VoiceState extends BaseClass {
 	channel_id: string;
 
 	@JoinColumn({ name: "channel_id" })
-	@ManyToOne(() => Channel)
+	@ManyToOne(() => Channel, {
+		onDelete: "CASCADE",
+	})
 	channel: Channel;
 
 	@Column({ nullable: true })
@@ -29,11 +33,15 @@ export class VoiceState extends BaseClass {
 	user_id: string;
 
 	@JoinColumn({ name: "user_id" })
-	@ManyToOne(() => User)
+	@ManyToOne(() => User, {
+		onDelete: "CASCADE",
+	})
 	user: User;
 
 	// @JoinColumn([{ name: "user_id", referencedColumnName: "id" },{ name: "guild_id", referencedColumnName: "guild_id" }])
-	// @ManyToOne(() => Member)
+	// @ManyToOne(() => Member, {
+	// 	onDelete: "CASCADE",
+	// })
 	//TODO find a way to make it work without breaking Guild.voice_states
 	member: Member;
 
diff --git a/util/src/entities/Webhook.ts b/util/src/entities/Webhook.ts
index 12ba0d08..8382435f 100644
--- a/util/src/entities/Webhook.ts
+++ b/util/src/entities/Webhook.ts
@@ -32,7 +32,9 @@ export class Webhook extends BaseClass {
 	guild_id: string;
 
 	@JoinColumn({ name: "guild_id" })
-	@ManyToOne(() => Guild)
+	@ManyToOne(() => Guild, {
+		onDelete: "CASCADE",
+	})
 	guild: Guild;
 
 	@Column({ nullable: true })
@@ -40,7 +42,9 @@ export class Webhook extends BaseClass {
 	channel_id: string;
 
 	@JoinColumn({ name: "channel_id" })
-	@ManyToOne(() => Channel)
+	@ManyToOne(() => Channel, {
+		onDelete: "CASCADE",
+	})
 	channel: Channel;
 
 	@Column({ nullable: true })
@@ -48,7 +52,9 @@ export class Webhook extends BaseClass {
 	application_id: string;
 
 	@JoinColumn({ name: "application_id" })
-	@ManyToOne(() => Application)
+	@ManyToOne(() => Application, {
+		onDelete: "CASCADE",
+	})
 	application: Application;
 
 	@Column({ nullable: true })
@@ -56,7 +62,9 @@ export class Webhook extends BaseClass {
 	user_id: string;
 
 	@JoinColumn({ name: "user_id" })
-	@ManyToOne(() => User)
+	@ManyToOne(() => User, {
+		onDelete: "CASCADE",
+	})
 	user: User;
 
 	@Column({ nullable: true })
@@ -64,6 +72,8 @@ export class Webhook extends BaseClass {
 	source_guild_id: string;
 
 	@JoinColumn({ name: "source_guild_id" })
-	@ManyToOne(() => Guild)
+	@ManyToOne(() => Guild, {
+		onDelete: "CASCADE",
+	})
 	source_guild: Guild;
 }
diff --git a/util/src/util/Database.ts b/util/src/util/Database.ts
index d3844cd9..c22d8abd 100644
--- a/util/src/util/Database.ts
+++ b/util/src/util/Database.ts
@@ -21,7 +21,7 @@ export function initDatabase() {
 		//
 		entities: Object.values(Models).filter((x) => x.constructor.name !== "Object"),
 		synchronize: true,
-		logging: false,
+		logging: true,
 		cache: {
 			duration: 1000 * 3, // cache all find queries for 3 seconds
 		},