sql.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { literal, Model, ModelStatic } from 'sequelize'
  2. import { forceNumber } from '@shared/core-utils'
  3. import { AttributesOnly } from '@shared/typescript-utils'
  4. function buildLocalAccountIdsIn () {
  5. return literal(
  6. '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
  7. )
  8. }
  9. function buildLocalActorIdsIn () {
  10. return literal(
  11. '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
  12. )
  13. }
  14. function buildBlockedAccountSQL (blockerIds: number[]) {
  15. const blockerIdsString = blockerIds.join(', ')
  16. return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
  17. ' UNION ' +
  18. 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
  19. 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
  20. 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
  21. }
  22. function buildServerIdsFollowedBy (actorId: any) {
  23. const actorIdNumber = forceNumber(actorId)
  24. return '(' +
  25. 'SELECT "actor"."serverId" FROM "actorFollow" ' +
  26. 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
  27. 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
  28. ')'
  29. }
  30. function buildSQLAttributes<M extends Model> (options: {
  31. model: ModelStatic<M>
  32. tableName: string
  33. excludeAttributes?: Exclude<keyof AttributesOnly<M>, symbol>[]
  34. aliasPrefix?: string
  35. }) {
  36. const { model, tableName, aliasPrefix, excludeAttributes } = options
  37. const attributes = Object.keys(model.getAttributes()) as Exclude<keyof AttributesOnly<M>, symbol>[]
  38. return attributes
  39. .filter(a => {
  40. if (!excludeAttributes) return true
  41. if (excludeAttributes.includes(a)) return false
  42. return true
  43. })
  44. .map(a => {
  45. return `"${tableName}"."${a}" AS "${aliasPrefix || ''}${a}"`
  46. })
  47. }
  48. // ---------------------------------------------------------------------------
  49. export {
  50. buildSQLAttributes,
  51. buildBlockedAccountSQL,
  52. buildServerIdsFollowedBy,
  53. buildLocalAccountIdsIn,
  54. buildLocalActorIdsIn
  55. }