1 import { BindOrReplacements, Op, QueryTypes, Sequelize } from 'sequelize'
2 import validator from 'validator'
3 import { forceNumber } from '@shared/core-utils'
5 function doesExist (sequelize: Sequelize, query: string, bind?: BindOrReplacements) {
7 type: QueryTypes.SELECT as QueryTypes.SELECT,
12 return sequelize.query(query, options)
13 .then(results => results.length === 1)
16 function createSimilarityAttribute (col: string, value: string) {
20 searchTrigramNormalizeCol(col),
22 searchTrigramNormalizeValue(value)
26 function buildWhereIdOrUUID (id: number | string) {
27 return validator.isInt('' + id) ? { id } : { uuid: id }
30 function parseAggregateResult (result: any) {
33 const total = forceNumber(result)
34 if (isNaN(total)) return 0
39 function parseRowCountResult (result: any) {
40 if (result.length !== 0) return result[0].total
45 function createSafeIn (sequelize: Sequelize, toEscape: (string | number)[], additionalUnescaped: string[] = []) {
46 return toEscape.map(t => {
49 : sequelize.escape('' + t)
50 }).concat(additionalUnescaped).join(', ')
53 function searchAttribute (sourceField?: string, targetField?: string) {
54 if (!sourceField) return {}
59 [Op.iLike as any]: `%${sourceField}%`
66 createSimilarityAttribute,
74 // ---------------------------------------------------------------------------
76 function searchTrigramNormalizeValue (value: string) {
77 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
80 function searchTrigramNormalizeCol (col: string) {
81 return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))