X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Fhelpers%2Fdatabase-utils.ts;h=7befa2c4955b934f397c6ccaf7781fe795e4c8c5;hb=1f256e7d3cf056c2d999260155cdba58ae1b878b;hp=6c5068fb0d631622d21e4fab74f6262dde5d1a2d;hpb=2284f202070aa2e49156cc52b3b1596a7d5aadec;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/helpers/database-utils.ts b/server/helpers/database-utils.ts index 6c5068fb0..7befa2c49 100644 --- a/server/helpers/database-utils.ts +++ b/server/helpers/database-utils.ts @@ -1,8 +1,17 @@ import * as retry from 'async/retry' import * as Bluebird from 'bluebird' +import { QueryTypes, Transaction } from 'sequelize' import { Model } from 'sequelize-typescript' +import { sequelizeTypescript } from '@server/initializers/database' import { logger } from './logger' -import { Transaction } from 'sequelize' + +function retryTransactionWrapper ( + functionToRetry: (arg1: A, arg2: B, arg3: C, arg4: D) => Promise | Bluebird, + arg1: A, + arg2: B, + arg3: C, + arg4: D, +): Promise function retryTransactionWrapper ( functionToRetry: (arg1: A, arg2: B, arg3: C) => Promise | Bluebird, @@ -59,7 +68,7 @@ function transactionRetryer (func: (err: any, data: T) => any) { }) } -function updateInstanceWithAnother > (instanceToUpdate: Model, baseInstance: Model) { +function updateInstanceWithAnother > (instanceToUpdate: T, baseInstance: U) { const obj = baseInstance.toJSON() for (const key of Object.keys(obj)) { @@ -79,6 +88,27 @@ function afterCommitIfTransaction (t: Transaction, fn: Function) { return fn() } +function deleteNonExistingModels > ( + fromDatabase: T[], + newModels: T[], + t: Transaction +) { + return fromDatabase.filter(f => !newModels.find(newModel => newModel.hasSameUniqueKeysThan(f))) + .map(f => f.destroy({ transaction: t })) +} + +// 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 + } + ) +} + // --------------------------------------------------------------------------- export { @@ -86,5 +116,7 @@ export { retryTransactionWrapper, transactionRetryer, updateInstanceWithAnother, - afterCommitIfTransaction + afterCommitIfTransaction, + deleteNonExistingModels, + setAsUpdated }