How to use the sequelize.literal function in sequelize

To help you get started, we’ve selected a few sequelize examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github opencollective / opencollective-api / server / graphql / v1 / CollectiveInterface.js View on Github external
query.where.isActive = args.isActive;
        } else if (typeof args.isArchived !== 'undefined') {
          query.where.isArchived = args.isArchived;
        }

        /* if any specific Expense status was passed */
        if (args.expenseStatus) {
          /* The escape trick came from here:
             https://github.com/sequelize/sequelize/issues/1132

             Didin't really find a better way to do it. */
          const status = SqlString.escape(args.expenseStatus.toUpperCase());
          query.where.expenseCount = sequelize.where(
            /* This tests if collective has any expenses in the given
             * status. */
            sequelize.literal(
              '(SELECT COUNT("id") FROM "Expenses" WHERE "Expenses"."CollectiveId" =' +
                ` "Collective"."id" AND "status" = ${status})`,
              args.expenseStatus,
            ),
            '>',
            0,
          );
        }
        const result = await models.Collective.findAndCountAll(query);
        const { count, rows } = result;
        return {
          total: count,
          collectives: rows,
          limit: args.limit,
          offset: args.offset,
        };
github magma / magma / nms / app / fbcnms-packages / fbcnms-sequelize-models / index.js View on Github external
export function jsonArrayContains(column: string, value: string) {
  if (
    sequelize.getDialect() === 'mysql' ||
    sequelize.getDialect() === 'mariadb'
  ) {
    return Sequelize.fn('JSON_CONTAINS', Sequelize.col(column), `"${value}"`);
  } else {
    // sqlite
    const escapedColumn = sequelize
      .getQueryInterface()
      .quoteIdentifier(column, true);
    const innerQuery = Sequelize.literal(
      `(SELECT 1 FROM json_each(${escapedColumn})` +
        `WHERE json_each.value = ${sequelize.escape(value)})`,
    );
    return Sequelize.where(innerQuery, 'IS', Sequelize.literal('NOT NULL'));
  }
}
github RiseVision / rise-node / packages / core-consensus-dpos / src / modules / delegates.ts View on Github external
attributes: ['forgingPK'],
      include: [
        {
          attributes: ['senderId'],
          model: this.transactionsModel,
          where: {
            height: {
              [round === 1 ? Op.lte : Op.lt]: this.roundsLogic.firstInRound(
                round
              ),
            },
            senderId: rows.map((r) => r.address),
          },
        },
      ],
      order: [sequelize.literal('"tx"."height" ASC')],
      raw: true,
    });

    const correctFKByAddr: { [addr: string]: Buffer & As<'publicKey'> } = {};
    // Since it's ordered by height ASC, we know for sure that most recent
    // entry will be the one set here.
    for (const fk of prevForgingKeys) {
      correctFKByAddr[fk['tx.senderId']] = fk.forgingPK;
    }

    const sortingParam = this.dposV2Helper.isV1(height)
      ? 'vote'
      : 'votesWeight';
    return rows
      .sort((a, b) => {
        if (a[sortingParam] === b[sortingParam]) {
github midwayjs / sandbox / packages / sandbox-core / src / core / manager / errorManager.ts View on Github external
private findErrorTypeDist(required: object[]) {
    const downSampling = Sequelize.literal('(unix_timestamp - unix_timestamp % 60)');
    const conditions: SearchCondition = {
      attributes: [
        ['error_type', 'errType'],
        [Sequelize.fn('COUNT', Sequelize.literal('*')), 'cnt'],
        [downSampling, 'timestamp'],
      ],
      where: { [Sequelize.Op.and]: required },
      group: [downSampling, 'errType'],
      order: [['timestamp', 'DESC']],
      raw: true,
    };
    return this.errorModel.findAll(conditions);
  }
}
github iGeeky / wolf / server / src / controllers / rbac.js View on Github external
async getResource(query) {
    const {appID, action, name} = query;
    const where = {appID: appID}
    where.action = {[Op.in]: [action, 'ALL']}
    where[Op.or] = [
      {matchType: 'equal', name: name},
      {matchType: 'suffix', name: Sequelize.literal(`right('${name}', length(name)) = name`)},
      {matchType: 'prefix', name: Sequelize.literal(`substr('${name}', 1, length(name)) = name`)},
    ]

    const order = [['priority', 'ASC']]
    const options = {where, order}

    const resource = await ResourceModel.findOne(options)
    return resource
  }
github staeco / iris-ql / src / types / functions.js View on Github external
  execute: () => types.fn('count', types.literal('*'))
}
github woss / graphql-to-sql / src / parsers / prisma.ts View on Github external
getDefaultValueFromPrisma(defaultValue, type) {
    let t = null
    if (typeof type !== 'string') {
      return t
    }

    switch (type) {
      case 'DateTime':
        t = Sequelize.literal('CURRENT_TIMESTAMP')
        break
      case 'UUID':
        t = Sequelize.literal('uuid_generate_v4()')
        break
      default:
        t = defaultValue
        break
    }
    return t
  }
github Feverqwe / ytWatchBot / src / db.js View on Github external
cleanChats() {
    return this.model.Chat.destroy({
      where: {
        id: {[Op.notIn]: Sequelize.literal(`(SELECT DISTINCT chatId FROM chatIdChannelId)`)},
        parentChatId: null
      }
    });
  }
github midwayjs / sandbox / packages / sandbox-core / src / core / manager / errorManager.ts View on Github external
private findErrorTypeBy(required: object[]) {
    const conditions: SearchCondition = {
      attributes: [
        ['error_type', 'errType'],
        [Sequelize.fn('COUNT', Sequelize.literal('*')), 'cnt'],
      ],
      where: { [Sequelize.Op.and]: required },
      group: ['errType'],
      raw: true,
    };
    return this.errorModel.findAll(conditions);
  }
github woss / graphql-to-sql / src / parsers / prisma.ts View on Github external
transformField(field: IGQLField) {
    const {isId, type, defaultValue, isUnique} = field

    let ret: DefineAttributeColumnOptions = {
      primaryKey: isId,
      defaultValue: defaultValue
        ? Sequelize.literal(defaultValue)
        : this.getDefaultValueFromPrisma(defaultValue, type),
      type: this.getSqlTypeFromPrisma(type),
      unique: isUnique,
    }
    if (type === 'ID') {
      ret.autoIncrement = true
      delete ret.defaultValue
    }

    return ret
  }
  protected cleanRelations(): ItableDefinition[] {

sequelize

Sequelize is a promise-based Node.js ORM tool for Postgres, MySQL, MariaDB, SQLite, Microsoft SQL Server, Amazon Redshift and Snowflake’s Data Cloud. It features solid transaction support, relations, eager and lazy loading, read replication and more.

MIT
Latest version published 28 days ago

Package Health Score

95 / 100
Full package analysis