How to use the sequelize.col 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 flow-typed / flow-typed / definitions / npm / sequelize_v4.x.x / flow_v0.42.x- / test_sequelize.js View on Github external
if (typeof val === "string") {
        val = val.toLowerCase();
      } else {
        throw new Error("email must be a string");
      }
      this.setDataValue("email", val);
    }
  }
}, {
  timestamps: false,
  indexes: [
    {
      name: "DefineOptionsIndexesTest_lower_email",
      unique: true,
      fields: [
        Sequelize.fn("LOWER", Sequelize.col("email"))
      ]
    }
  ]
} );

//
//  Transaction
// ~~~~~~~~~~~~~
//
//  https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/transaction.test.js
//

s.transaction().then( function( t ) {

  t.commit();
  t.rollback();
github Hydractify / kanna_kobayashi / src / commands / user / item.ts View on Github external
protected async find(message: Message, args: string[], authorModel: UserModel): Promise {
		const item: Item | null = await Item.findOne({
			include: [{
				as: 'holders',
				model: UserModel,
				required: false,
				through: { attributes: ['count'] },
				where: { id: message.author.id },
			}],
			where: where(fn('lower', col('name')), args.join(' ').toLowerCase()) as {},
		});
		if (!item) return message.reply('could not find an item with that name!');

		const embed: MessageEmbed = MessageEmbed.common(message, authorModel)
			.setAuthor(
				`Information about the ${item.type.toLowerCase()} "${titleCase(item.name)}"`,
				this.client.user.displayAvatarURL(),
			)
			.setThumbnail(message.guild.iconURL())
			.setDescription(item.description || '\u200b');

		for (let [title, value] of Object.entries(item.toJSON())) {
			// Don't show price for non buyable items
			if ((title === 'price' && value === null)
				// Already in the description of the embed.
				|| title === 'description') continue;
github RiseVision / rise-node / packages / core-consensus-dpos / src / modules / delegates.ts View on Github external
private async replaceEndForger(height: number, round: number) {
    // Gets all "recent" blocks forged exactly at the end of round to find the producer who should be the next one
    // to forge in last position (and so to skip next round), sorted by Max height and grouped by generatorPublicKey
    const res: any = await this.blocksModel.findAll({
      attributes: [
        [sequelize.fn('MAX', sequelize.col('height')), 'lastRoundEndHeight'],
        'generatorPublicKey',
      ],
      group: 'generatorPublicKey',
      order: sequelize.literal('"lastRoundEndHeight" ASC'),
      raw: true,
      where: {
        [Op.and]: [
          {
            height: {
              [Op.gte]:
                height -
                this.slots.delegates *
                  this.dposConstants.dposv2.delegatesPoolSize,
              [Op.lt]: height,
            },
          },
github volumio / Volumio2 / app / plugins / music_service / music_library / index.js View on Github external
MusicLibrary.prototype.searchAlbums = function(sequelizeQueryOptions) {
	var self = this;

	sequelizeQueryOptions = sequelizeQueryOptions || {};
	sequelizeQueryOptions.attributes = sequelizeQueryOptions.attributes || [];
	sequelizeQueryOptions.attributes.push(
		// It's not clear, but 'DISTINCT' works for 'artist' as well
		[Sequelize.fn('DISTINCT', Sequelize.col('album')), 'album'],
		'artist',
		[Sequelize.literal('(SELECT location FROM AudioMetadata AS innerData WHERE innerData.artist = artist AND innerData.album = album LIMIT 1)'), 'trackLocation'],
		[Sequelize.literal('(SELECT year FROM AudioMetadata AS innerData WHERE innerData.artist = artist AND innerData.album = album LIMIT 1)'), 'year'],
		// SQLITE specific:
		// When we use aggregated function we have to specify 'AudioMetadata' explicitly
		// Otherwise we have NOT specify
		[Sequelize.literal('(SELECT sum(duration) FROM AudioMetadata AS innerData WHERE innerData.artist = AudioMetadata.artist AND innerData.album = AudioMetadata.album)'), 'duration'],
	);

	//
	return this.query(sequelizeQueryOptions).then(function(records) {
		return records.map(function(record) {
			return {
				artist: record.artist,
				album: record.album,
				trackLocation: record.dataValues.trackLocation,
github Hydractify / kanna_kobayashi / src / commands / common / commandUsage.ts View on Github external
public async run(message: GuildMessage, _: string[], { authorModel }: ICommandRunInfo): Promise
	{
		const [thisMonth, lastHour]: [CommandLog[], CommandLog[]] = await Promise.all([
			CommandLog.findAll({
				attributes: [[fn('COUNT', col('command_name')), 'count'], ['command_name', 'commandName']],
				group: ['commandName'],
				order: [['count', 'DESC']],
			}),
			CommandLog.findAll({
				attributes: [[fn('COUNT', col('command_name')), 'count'], ['command_name', 'commandName']],
				group: ['commandName'],
				order: [['count', 'DESC']],
				where: { run: { [Op.gt]: Date.now() - 35e5 } },
			}),
		]);

		let allTimeCount: number = 0;
		const thisMonthTop5: string[] = [];
		/* eslint-disable-next-line prefer-const */
		for (let { dataValues: { count, commandName } } of thisMonth as any)
		{
github keenwon / eazydict / src / dao / HistoryDao.js View on Github external
async function getHistoryCount () {
  let count

  try {
    const historyModel = await new HistoryModel()

    const data = await historyModel.findOne({
      attributes: [[sequelize.fn('COUNT', sequelize.col('id')), 'num']]
    })

    count = data.dataValues.num
  } catch (err) {
    debug(err)
    count = '未知'
  }

  return count
}
github CodeChain-io / codechain-indexer / src / models / logic / utxo.ts View on Github external
{ [Sequelize.Op.eq]: null }
                    ]
                },
                blockNumber: {
                    [Sequelize.Op.lte]: blockNumber
                }
            },
            attributes: [
                [
                    Sequelize.fn("SUM", Sequelize.col("quantity")),
                    "totalAssetQuantity"
                ],
                "address",
                "assetType",
                [
                    Sequelize.fn("COUNT", Sequelize.col("UTXO.assetType")),
                    "utxoQuantity"
                ]
            ],
            order: Sequelize.literal(
                `"totalAssetQuantity" DESC, "assetType" DESC`
            ),
            include: [
                {
                    as: "assetScheme",
                    model: models.AssetScheme
                }
            ],
            group: ["UTXO.address", "UTXO.assetType", "assetScheme.assetType"]
        }).then(instances =>
            instances.map(instance => instance.get({ plain: true }))
        );
github bitvagas / bitvagas / app / modules / jobs / controllers / job-controller.js View on Github external
, findByTitle : function(request, response, next, title){
        db.job.findOne({
          where: Sequelize.where(Sequelize.fn('lower', Sequelize.col('TITLE')),
                                 Sequelize.fn('lower', title))
          , include : includes
        }).then(function(job){
            if(!job)
                response.status(400).json({ message : "errorMessage.job.not.found" });

            request.job = job;
            next();
        }).catch(function(err){
            next(err);
        });
    }
};
github delbertbeta / rajio / tool / gc.js View on Github external
const garbageCollection = async () => {
  const garbages = await sequelize.rajio.findAll({
    where: {
      [Op.or]: {
        "downloadCount": {
          [Op.gte]: Sequelize.col('downloadLimit')
        },
        "timeLimit": {
          [Op.lte]: new Date()
        }
      },
      "deleted": {
        [Op.not]: true
      }
    }
  })
  garbages.forEach(v => {
    v.deleted = true
    fs.removeSync(path.resolve(`./data/upload/${v.id}`))
    v.save()
  })
}

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