]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/models/utils.ts
Add index for recently added SQL query
[github/Chocobozzz/PeerTube.git] / server / models / utils.ts
CommitLineData
3caf77d3 1import { Model, Sequelize } from 'sequelize-typescript'
418d092a 2import * as validator from 'validator'
1735c825 3import { Col } from 'sequelize/types/lib/utils'
d7a25329 4import { literal, OrderItem } from 'sequelize'
57c36b27 5
95153292 6type SortType = { sortModel: string, sortValue: string }
06215f15 7
9a629c6e 8// Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ]
1735c825
C
9function getSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
10 const { direction, field } = buildDirectionAndField(value)
11
12 let finalField: string | Col
4b54f136
C
13
14 if (field.toLowerCase() === 'match') { // Search
1735c825 15 finalField = Sequelize.col('similarity')
aa3796bd
C
16 } else if (field === 'videoQuotaUsed') { // Users list
17 finalField = Sequelize.col('videoQuotaUsed')
1735c825
C
18 } else {
19 finalField = field
4b54f136 20 }
5c39adb7 21
1735c825 22 return [ [ finalField, direction ], lastSort ]
9a629c6e
C
23}
24
1735c825
C
25function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
26 const { direction, field } = buildDirectionAndField(value)
5c39adb7 27
1735c825 28 if (field.toLowerCase() === 'trending') { // Sort by aggregation
9a629c6e
C
29 return [
30 [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
31
32 [ Sequelize.col('VideoModel.views'), direction ],
33
34 lastSort
35 ]
36 }
37
1735c825
C
38 let finalField: string | Col
39
40 // Alias
41 if (field.toLowerCase() === 'match') { // Search
42 finalField = Sequelize.col('similarity')
43 } else {
44 finalField = field
45 }
46
47 const firstSort = typeof finalField === 'string'
48 ? finalField.split('.').concat([ direction ]) as any // FIXME: sequelize typings
49 : [ finalField, direction ]
afa4374a
C
50
51 return [ firstSort, lastSort ]
5c39adb7
C
52}
53
95153292 54function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
1735c825 55 const [ firstSort ] = getSort(value)
792dbaf0 56
95153292 57 if (model) return [ [ literal(`"${model}.${firstSort[ 0 ]}" ${firstSort[ 1 ]}`) ], lastSort ] as any[] // FIXME: typings
3bb6c526 58 return [ firstSort, lastSort ]
792dbaf0
GS
59}
60
cb5ce4cb
C
61function getFollowsSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
62 const { direction, field } = buildDirectionAndField(value)
63
64 if (field === 'redundancyAllowed') {
65 return [
66 [ 'ActorFollowing', 'Server', 'redundancyAllowed', direction ],
67 lastSort
68 ]
69 }
70
71 return getSort(value, lastSort)
72}
73
9f79ade6
C
74function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
75 const now = Date.now()
76 const createdAtTime = model.createdAt.getTime()
77 const updatedAtTime = model.updatedAt.getTime()
78
79 return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
80}
81
1735c825
C
82function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
83 if (nullable && (value === null || value === undefined)) return
84
3fd3ab2d
C
85 if (validator(value) === false) {
86 throw new Error(`"${value}" is not a valid ${fieldName}.`)
87 }
88}
89
57c36b27
C
90function buildTrigramSearchIndex (indexName: string, attribute: string) {
91 return {
92 name: indexName,
93 fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
94 using: 'gin',
95 operator: 'gin_trgm_ops'
96 }
97}
98
99function createSimilarityAttribute (col: string, value: string) {
100 return Sequelize.fn(
101 'similarity',
102
103 searchTrigramNormalizeCol(col),
104
105 searchTrigramNormalizeValue(value)
106 )
107}
108
7ad9b984
C
109function buildBlockedAccountSQL (serverAccountId: number, userAccountId?: number) {
110 const blockerIds = [ serverAccountId ]
111 if (userAccountId) blockerIds.push(userAccountId)
112
113 const blockerIdsString = blockerIds.join(', ')
114
418d092a 115 return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
7ad9b984 116 ' UNION ALL ' +
7ad9b984
C
117 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
118 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
119 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
418d092a
C
120}
121
122function buildServerIdsFollowedBy (actorId: any) {
123 const actorIdNumber = parseInt(actorId + '', 10)
124
125 return '(' +
126 'SELECT "actor"."serverId" FROM "actorFollow" ' +
127 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
128 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
129 ')'
130}
7ad9b984 131
418d092a
C
132function buildWhereIdOrUUID (id: number | string) {
133 return validator.isInt('' + id) ? { id } : { uuid: id }
7ad9b984
C
134}
135
3acc5084
C
136function parseAggregateResult (result: any) {
137 if (!result) return 0
138
139 const total = parseInt(result + '', 10)
140 if (isNaN(total)) return 0
141
142 return total
143}
144
6b9c966f
C
145const createSafeIn = (model: typeof Model, stringArr: (string | number)[]) => {
146 return stringArr.map(t => model.sequelize.escape('' + t))
3caf77d3
C
147 .join(', ')
148}
149
6b9c966f
C
150function buildLocalAccountIdsIn () {
151 return literal(
152 '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
153 )
154}
155
156function buildLocalActorIdsIn () {
157 return literal(
158 '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
159 )
160}
161
5c39adb7
C
162// ---------------------------------------------------------------------------
163
65fcc311 164export {
7ad9b984 165 buildBlockedAccountSQL,
6b9c966f 166 buildLocalActorIdsIn,
06215f15 167 SortType,
6b9c966f 168 buildLocalAccountIdsIn,
792dbaf0 169 getSort,
9a629c6e 170 getVideoSort,
95153292 171 getBlacklistSort,
57c36b27
C
172 createSimilarityAttribute,
173 throwIfNotValid,
418d092a
C
174 buildServerIdsFollowedBy,
175 buildTrigramSearchIndex,
9f79ade6 176 buildWhereIdOrUUID,
3acc5084 177 isOutdated,
3caf77d3 178 parseAggregateResult,
cb5ce4cb 179 getFollowsSort,
3caf77d3 180 createSafeIn
57c36b27
C
181}
182
183// ---------------------------------------------------------------------------
184
185function searchTrigramNormalizeValue (value: string) {
2cebd797 186 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
57c36b27
C
187}
188
189function searchTrigramNormalizeCol (col: string) {
190 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
65fcc311 191}
9a629c6e
C
192
193function buildDirectionAndField (value: string) {
1735c825 194 let field: string
9a629c6e
C
195 let direction: 'ASC' | 'DESC'
196
197 if (value.substring(0, 1) === '-') {
198 direction = 'DESC'
199 field = value.substring(1)
200 } else {
201 direction = 'ASC'
202 field = value
203 }
204
205 return { direction, field }
206}