ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

query.ts 2.3 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { forceNumber } from '@peertube/peertube-core-utils'
  2. import { BindOrReplacements, Op, QueryOptionsWithType, QueryTypes, Sequelize, Transaction } from 'sequelize'
  3. import { Fn } from 'sequelize/types/utils'
  4. import validator from 'validator'
  5. async function doesExist (options: {
  6. sequelize: Sequelize
  7. query: string
  8. bind?: BindOrReplacements
  9. transaction?: Transaction
  10. }) {
  11. const { sequelize, query, bind, transaction } = options
  12. const queryOptions: QueryOptionsWithType<QueryTypes.SELECT> = {
  13. type: QueryTypes.SELECT,
  14. bind,
  15. raw: true,
  16. transaction
  17. }
  18. const results = await sequelize.query(query, queryOptions)
  19. return results.length === 1
  20. }
  21. // FIXME: have to specify the result type to not break peertube typings generation
  22. function createSimilarityAttribute (col: string, value: string): Fn {
  23. return Sequelize.fn(
  24. 'similarity',
  25. searchTrigramNormalizeCol(col),
  26. searchTrigramNormalizeValue(value)
  27. )
  28. }
  29. function buildWhereIdOrUUID (id: number | string) {
  30. return validator.default.isInt('' + id) ? { id } : { uuid: id }
  31. }
  32. function parseAggregateResult (result: any) {
  33. if (!result) return 0
  34. const total = forceNumber(result)
  35. if (isNaN(total)) return 0
  36. return total
  37. }
  38. function parseRowCountResult (result: any) {
  39. if (result.length !== 0) return result[0].total
  40. return 0
  41. }
  42. function createSafeIn (sequelize: Sequelize, toEscape: (string | number)[], additionalUnescaped: string[] = []) {
  43. return toEscape.map(t => {
  44. return t === null
  45. ? null
  46. : sequelize.escape('' + t)
  47. }).concat(additionalUnescaped).join(', ')
  48. }
  49. function searchAttribute (sourceField?: string, targetField?: string) {
  50. if (!sourceField) return {}
  51. return {
  52. [targetField]: {
  53. // FIXME: ts error
  54. [Op.iLike as any]: `%${sourceField}%`
  55. }
  56. }
  57. }
  58. export {
  59. buildWhereIdOrUUID, createSafeIn, createSimilarityAttribute, doesExist, parseAggregateResult,
  60. parseRowCountResult, searchAttribute
  61. }
  62. // ---------------------------------------------------------------------------
  63. function searchTrigramNormalizeValue (value: string) {
  64. return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
  65. }
  66. function searchTrigramNormalizeCol (col: string) {
  67. return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
  68. }