1 import { Sequelize } from 'sequelize'
2 import { AbstractRunQuery } from '@server/models/shared'
3 import { ActorImageType } from '@shared/models'
4 import { getInstanceFollowsSort } from '../../../shared'
5 import { ActorFollowTableAttributes } from './actor-follow-table-attributes'
13 export abstract class InstanceListFollowsQueryBuilder <T extends BaseOptions> extends AbstractRunQuery {
14 protected readonly tableAttributes = new ActorFollowTableAttributes()
16 protected innerQuery: string
19 protected readonly sequelize: Sequelize,
20 protected readonly options: T
25 protected abstract getWhere (): string
27 protected getJoins () {
28 return 'INNER JOIN "actor" "ActorFollower" ON "ActorFollower"."id" = "ActorFollowModel"."actorId" ' +
29 'INNER JOIN "actor" "ActorFollowing" ON "ActorFollowing"."id" = "ActorFollowModel"."targetActorId" '
32 protected getServerJoin (actorName: string) {
33 return `LEFT JOIN "server" "${actorName}->Server" ON "${actorName}"."serverId" = "${actorName}->Server"."id" `
36 protected getAvatarsJoin (actorName: string) {
37 return `LEFT JOIN "actorImage" "${actorName}->Avatars" ON "${actorName}.id" = "${actorName}->Avatars"."actorId" ` +
38 `AND "${actorName}->Avatars"."type" = ${ActorImageType.AVATAR}`
41 private buildInnerQuery () {
42 this.innerQuery = `${this.getInnerSelect()} ` +
43 `FROM "actorFollow" AS "ActorFollowModel" ` +
44 `${this.getJoins()} ` +
45 `${this.getServerJoin('ActorFollowing')} ` +
46 `${this.getServerJoin('ActorFollower')} ` +
47 `${this.getWhere()} ` +
48 `${this.getOrder()} ` +
49 `LIMIT :limit OFFSET :offset `
51 this.replacements.limit = this.options.count
52 this.replacements.offset = this.options.start
55 protected buildListQuery () {
56 this.buildInnerQuery()
58 this.query = `${this.getSelect()} ` +
59 `FROM (${this.innerQuery}) AS "ActorFollowModel" ` +
60 `${this.getAvatarsJoin('ActorFollower')} ` +
61 `${this.getAvatarsJoin('ActorFollowing')} ` +
65 protected buildCountQuery () {
66 this.query = `SELECT COUNT(*) AS "total" ` +
67 `FROM "actorFollow" AS "ActorFollowModel" ` +
68 `${this.getJoins()} ` +
69 `${this.getServerJoin('ActorFollowing')} ` +
70 `${this.getServerJoin('ActorFollower')} ` +
74 private getInnerSelect () {
75 return this.buildSelect([
76 this.tableAttributes.getFollowAttributes(),
77 this.tableAttributes.getActorAttributes('ActorFollower'),
78 this.tableAttributes.getActorAttributes('ActorFollowing'),
79 this.tableAttributes.getServerAttributes('ActorFollower'),
80 this.tableAttributes.getServerAttributes('ActorFollowing')
84 private getSelect () {
85 return this.buildSelect([
86 '"ActorFollowModel".*',
87 this.tableAttributes.getAvatarAttributes('ActorFollower'),
88 this.tableAttributes.getAvatarAttributes('ActorFollowing')
93 const orders = getInstanceFollowsSort(this.options.sort)
95 return 'ORDER BY ' + orders.map(o => `"${o[0]}" ${o[1]}`).join(', ')