1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
|
import * as retry from 'async/retry'
import * as Bluebird from 'bluebird'
import { BindOrReplacements, QueryTypes, Transaction } from 'sequelize'
import { Model } from 'sequelize-typescript'
import { sequelizeTypescript } from '@server/initializers/database'
import { logger } from './logger'
function retryTransactionWrapper <T, A, B, C, D> (
functionToRetry: (arg1: A, arg2: B, arg3: C, arg4: D) => Promise<T>,
arg1: A,
arg2: B,
arg3: C,
arg4: D,
): Promise<T>
function retryTransactionWrapper <T, A, B, C> (
functionToRetry: (arg1: A, arg2: B, arg3: C) => Promise<T>,
arg1: A,
arg2: B,
arg3: C
): Promise<T>
function retryTransactionWrapper <T, A, B> (
functionToRetry: (arg1: A, arg2: B) => Promise<T>,
arg1: A,
arg2: B
): Promise<T>
function retryTransactionWrapper <T, A> (
functionToRetry: (arg1: A) => Promise<T>,
arg1: A
): Promise<T>
function retryTransactionWrapper <T> (
functionToRetry: () => Promise<T> | Bluebird<T>
): Promise<T>
function retryTransactionWrapper <T> (
functionToRetry: (...args: any[]) => Promise<T>,
...args: any[]
): Promise<T> {
return transactionRetryer<T>(callback => {
functionToRetry.apply(null, args)
.then((result: T) => callback(null, result))
.catch(err => callback(err))
})
.catch(err => {
logger.error(`Cannot execute ${functionToRetry.name} with many retries.`, { err })
throw err
})
}
function transactionRetryer <T> (func: (err: any, data: T) => any) {
return new Promise<T>((res, rej) => {
retry(
{
times: 5,
errorFilter: err => {
const willRetry = (err.name === 'SequelizeDatabaseError')
logger.debug('Maybe retrying the transaction function.', { willRetry, err, tags: [ 'sql', 'retry' ] })
return willRetry
}
},
func,
(err, data) => err ? rej(err) : res(data)
)
})
}
// ---------------------------------------------------------------------------
function updateInstanceWithAnother <M, T extends U, U extends Model<M>> (instanceToUpdate: T, baseInstance: U) {
const obj = baseInstance.toJSON()
for (const key of Object.keys(obj)) {
instanceToUpdate[key] = obj[key]
}
}
function resetSequelizeInstance (instance: Model<any>, savedFields: object) {
Object.keys(savedFields).forEach(key => {
instance[key] = savedFields[key]
})
}
function filterNonExistingModels <T extends { hasSameUniqueKeysThan (other: T): boolean }> (
fromDatabase: T[],
newModels: T[]
) {
return fromDatabase.filter(f => !newModels.find(newModel => newModel.hasSameUniqueKeysThan(f)))
}
function deleteAllModels <T extends Pick<Model, 'destroy'>> (models: T[], transaction: Transaction) {
return Promise.all(models.map(f => f.destroy({ transaction })))
}
// Sequelize always skip the update if we only update updatedAt field
function setAsUpdated (table: string, id: number, transaction?: Transaction) {
return sequelizeTypescript.query(
`UPDATE "${table}" SET "updatedAt" = :updatedAt WHERE id = :id`,
{
replacements: { table, id, updatedAt: new Date() },
type: QueryTypes.UPDATE,
transaction
}
)
}
// ---------------------------------------------------------------------------
function runInReadCommittedTransaction <T> (fn: (t: Transaction) => Promise<T>) {
const options = { isolationLevel: Transaction.ISOLATION_LEVELS.READ_COMMITTED }
return sequelizeTypescript.transaction(options, t => fn(t))
}
function afterCommitIfTransaction (t: Transaction, fn: Function) {
if (t) return t.afterCommit(() => fn())
return fn()
}
// ---------------------------------------------------------------------------
function doesExist (query: string, bind?: BindOrReplacements) {
const options = {
type: QueryTypes.SELECT as QueryTypes.SELECT,
bind,
raw: true
}
return sequelizeTypescript.query(query, options)
.then(results => results.length === 1)
}
// ---------------------------------------------------------------------------
export {
resetSequelizeInstance,
retryTransactionWrapper,
transactionRetryer,
updateInstanceWithAnother,
afterCommitIfTransaction,
filterNonExistingModels,
deleteAllModels,
setAsUpdated,
runInReadCommittedTransaction,
doesExist
}
|