From 8c4bbd946d2247c2e239cbbf8773d2d31c1a57aa Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 10 Jan 2023 11:09:30 +0100 Subject: Refactor model utils --- server/models/shared/sql.ts | 68 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 server/models/shared/sql.ts (limited to 'server/models/shared/sql.ts') diff --git a/server/models/shared/sql.ts b/server/models/shared/sql.ts new file mode 100644 index 000000000..5aaeb49f0 --- /dev/null +++ b/server/models/shared/sql.ts @@ -0,0 +1,68 @@ +import { literal, Model, ModelStatic } from 'sequelize' +import { forceNumber } from '@shared/core-utils' +import { AttributesOnly } from '@shared/typescript-utils' + +function buildLocalAccountIdsIn () { + return literal( + '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)' + ) +} + +function buildLocalActorIdsIn () { + return literal( + '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)' + ) +} + +function buildBlockedAccountSQL (blockerIds: number[]) { + const blockerIdsString = blockerIds.join(', ') + + return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' + + ' UNION ' + + 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' + + 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' + + 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')' +} + +function buildServerIdsFollowedBy (actorId: any) { + const actorIdNumber = forceNumber(actorId) + + return '(' + + 'SELECT "actor"."serverId" FROM "actorFollow" ' + + 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' + + 'WHERE "actorFollow"."actorId" = ' + actorIdNumber + + ')' +} + +function buildSQLAttributes (options: { + model: ModelStatic + tableName: string + + excludeAttributes?: Exclude, symbol>[] + aliasPrefix?: string +}) { + const { model, tableName, aliasPrefix, excludeAttributes } = options + + const attributes = Object.keys(model.getAttributes()) as Exclude, symbol>[] + + return attributes + .filter(a => { + if (!excludeAttributes) return true + if (excludeAttributes.includes(a)) return false + + return true + }) + .map(a => { + return `"${tableName}"."${a}" AS "${aliasPrefix || ''}${a}"` + }) +} + +// --------------------------------------------------------------------------- + +export { + buildSQLAttributes, + buildBlockedAccountSQL, + buildServerIdsFollowedBy, + buildLocalAccountIdsIn, + buildLocalActorIdsIn +} -- cgit v1.2.3