How to use the QueryTypes function from sequelize

Find comprehensive JavaScript sequelize.QueryTypes code examples handpicked from public code repositorys.

sequelize.QueryTypes is an enumeration in the Sequelize library that defines different types of SQL queries.

404
405
406
407
408
409
410
411
412
413
const { id } = req.query;

let comments = [];

const selectCommands = await db.query("SELECT id,value,author_id,timestamp FROM cms_post_comments WHERE post_id = ? AND type = ? ORDER BY timestamp DESC", {
    replacements: [id, 'article'], type: sequelize.QueryTypes.SELECT
});

if (selectCommands.length > 0) {
    for (var i = 0; i < selectCommands.length; i++) {
fork icon3
star icon3
watch icon2

+ 233 other calls in file

225
226
227
228
229
230
231
232
233
234
        });
    };
}

const user = await db.query("SELECT id,username,motto,figure,last_online,online,rank,vip_points,credits,activity_points,seasonal_points,vip FROM players WHERE id = ?", {
    replacements: [player.id], type: sequelize.QueryTypes.SELECT
});


var userArray = [];
fork icon3
star icon3
watch icon2

+ 103 other calls in file

How does sequelize.QueryTypes work?

sequelize.QueryTypes works by defining a set of constants that represent different types of SQL queries that can be executed using Sequelize.

The enumeration provides constants for the following types of queries:

  • SELECT: A SELECT query that retrieves data from a database table.
  • INSERT: An INSERT query that inserts data into a database table.
  • UPDATE: An UPDATE query that updates data in a database table.
  • DELETE: A DELETE query that deletes data from a database table.
  • UPSERT: An UPSERT query that updates data in a database table if it exists, or inserts it if it does not.
  • BULK_INSERT: A bulk INSERT query that inserts multiple rows of data into a database table in a single query.
  • SHOW: A SHOW query that displays information about a database or database object.

By using sequelize.QueryTypes, developers can easily specify the type of query they want to execute when using Sequelize's query method. This can be useful when working with more complex queries that cannot be easily expressed using Sequelize's other query methods.

194
195
196
197
198
199
200
201
202
203
        status_code: 400, 
        message: i18n.__('registerGenderRequired')
    }); 
} else {
    const getTotalIp = await db.query("SELECT ip_last FROM players WHERE ip_last = ?", {
        replacements: [ requestIp.getClientIp(req)], type: sequelize.QueryTypes.SELECT
    });

    if (getTotalIp.length < config.get('cms_config').registerSettings.maxAccountsPerIp) {
        if (hCaptcha) {
fork icon3
star icon3
watch icon2

+ 25 other calls in file

5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
} else {
	if (searchString == '') {
		res.status(200).send({ data:{success : false, message: "Search string is required"} ,errorNode:{errorCode:1, errorMsg:"Error"}});
	} else {
		// var searchProductList = await sequelize.query("SELECT id, title, slug, price, specialPrice, size FROM `products` WHERE storeId = "+storeId+" and `title` LIKE '%"+searchString+"%' and status = 'active' and isConfigurable = 0",{ type: Sequelize.QueryTypes.SELECT });
		var searchProductList = await sequelize.query("SELECT id, title, slug, price, specialPrice  FROM `products` WHERE  storeId = "+storeId+"  and LOWER(`title`) LIKE LOWER('%"+searchString+"%') and status = 'active' and isConfigurable = 0",{ type: Sequelize.QueryTypes.SELECT });
	
		if(searchProductList.length >0){

			////////////////////////// catelog price rule start /////////////////////////////////////
fork icon0
star icon0
watch icon1

+ 230 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
const { Sequelize, QueryTypes } = require("sequelize");
const sequelize = new Sequelize("database", "username", "password", {
  dialect: "mysql",
});

async function getData() {
  const sql = "SELECT * FROM `users`";
  const results = await sequelize.query(sql, { type: QueryTypes.SELECT });

  console.log(results);
}

getData();

In this example, we use sequelize.QueryTypes to execute a SELECT query on a database table using Sequelize's query method. We first create a new Sequelize instance and define the connection parameters. We then define a SQL query string that selects all rows from a users table. We use sequelize.query() to execute the query, passing { type: QueryTypes.SELECT } as an option to specify the type of query to execute. The function returns an array of result rows, which is then logged to the console. By using sequelize.QueryTypes in this way, we can easily execute more complex SQL queries that cannot be easily expressed using Sequelize's other query methods.

12
13
14
15
16
17
18
19
20
const query = 'SELECT score FROM game1 WHERE user_id = :userId';
const result = await sequelize.query(query, {
  replacements: {
    userId: userId,
  },
  type: Sequelize.QueryTypes.SELECT
});

const nowScore = result[0];
fork icon0
star icon0
watch icon1

+ 17 other calls in file

42
43
44
45
46
47
48
49
50
    OR (acn.id = acb.NodeAffinity2 AND acb.NodeAffinity2 IS NOT NULL)
    OR (acn.id = acb.NodeAffinity3 AND acb.NodeAffinity3 IS NOT NULL)
    OR (acn.id = acb.NodeAffinity4 AND acb.NodeAffinity4 IS NOT NULL)
    OR (acn.id = acb.NodeAffinity5 AND acb.NodeAffinity5 IS NOT NULL)
  ${id ? `WHERE ac.id = ${id}` : ''}
  `, { type: Sequelize.QueryTypes.SELECT })

const mappedCharts = charts.reduce((prev, curr) => {
  const treeList = prev[curr.treeId];
fork icon0
star icon0
watch icon1

+ 14 other calls in file

40
41
42
43
44
45
46
47
48
// console.log(Uname)
Uname = Uname[0].name
// console.log(Uname[0].name)


let Uphone = await sequelize.query(`select mobile from users where email = "${data.Email}"`,{ type: Sequelize.QueryTypes.SELECT })
// console.log(Uphone)
Uphone =  Uphone[0].mobile
let Uemail = data.Email
fork icon0
star icon0
watch icon1

+ 11 other calls in file

256
257
258
259
260
261
262
263
264
265
      "isUpdated":"yes"
    });
  }
} 

var crossSellProductList = await sequelize.query("SELECT products.id, products.sku, products.title, products.slug, products.price, products.specialPrice, products.size, products.status, products.isConfigurable FROM `relatedProduct` left join products on products.id = relatedProduct.selectedProductId WHERE relatedProduct.storeId = "+storeId+" and relatedProduct.productId = "+productId+" and relatedProduct.type = 'Cross-Sells'",{ type: Sequelize.QueryTypes.SELECT });
if(crossSellProductList.length>0){
  for(var i = 0; i < crossSellProductList.length; i++){

    let upsellThumbnailProductImages = await models.productImages.findAll({attributes:['id','productId','file','imageTitle'],where:{productId:crossSellProductList[i].id, isPrimary: 'Yes'}});
fork icon0
star icon0
watch icon1

+ 62 other calls in file

100
101
102
103
104
105
106
107
108
109
var user = users.toJSON();

var reportingId = [];
if (users.storeId != null) {
	//*****Assign Reporting Users Start									
	//1var adminIds = await sequelize.query("SELECT ID.level, DATA.id FROM(SELECT @ids as _ids,( SELECT @ids := GROUP_CONCAT(id) FROM admins WHERE FIND_IN_SET(parentId, @ids) AND cid = "+user.cid+") as cids, @l := @l+1 as level FROM admins, (SELECT @ids :="+user.id+", @l := 0 ) b WHERE @ids IS NOT NULL AND cid = "+user.cid+") id, admins AS DATA WHERE FIND_IN_SET(DATA.id, ID._ids) ORDER BY level, id",{ type: Sequelize.QueryTypes.SELECT });
	var adminIds = await sequelize.query("SELECT DATA.id FROM(SELECT @ids as _ids,( SELECT @ids := GROUP_CONCAT(id) FROM admins WHERE FIND_IN_SET(parentId, @ids) AND storeId = " + user.storeId + ") as cids, @l := @l+1 as level FROM admins, (SELECT @ids :=" + user.id + ", @l := 0 ) b WHERE @ids IS NOT NULL AND storeId = " + user.storeId + ") id, admins AS DATA WHERE FIND_IN_SET(DATA.id, _ids) ORDER BY level, id", { type: Sequelize.QueryTypes.SELECT });
	//3var adminIds = await sequelize.query("WITH RECURSIVE descendant AS (SELECT  id,cid,parentId,0 AS level FROM admins WHERE id = "+user.id+" AND cid = "+user.cid+" UNION ALL SELECT  ft.id,ft.cid,ft.parentId,level + 1 FROM admins ft JOIN descendant d ON ft.parentId = d.id WHERE ft.cid = "+user.cid+" )SELECT  d.id AS id,d.cid AS cid,d.level FROM descendant d JOIN admins a ON d.parentId = a.id ORDER BY level",{ type: Sequelize.QueryTypes.SELECT });
	
	adminIds.forEach(function (admin) {
fork icon0
star icon0
watch icon1

+ 8 other calls in file

206
207
208
209
210
211
212
213
214
215
    offset: 0, 
})
user.dataValues.sessions_recent = sessions_recent;

let bytes_total = await sequelize.query("SELECT SUM(initiator_rxbytes) as total_rx,SUM(initiator_txbytes) as total_tx FROM enclaves where initiator_role LIKE $role and initiator_uid=$user_id group by initiator_uid",
{ bind: { role: 'U', user_id:user.id }, type: Sequelize.QueryTypes.SELECT });
if (bytes_total.length) {
    user.dataValues.bytes_total = bytes_total[0];
} else {
    user.dataValues.bytes_total =  { "total_rx": 0 , "total_tx": 0 };
fork icon0
star icon0
watch icon1

+ 15 other calls in file

129
130
131
132
133
134
135
136
137
138
    }] 
})
service.dataValues.enclave_list = enclave_list;    

let bytes_total = await sequelize.query("SELECT SUM(responder_rxbytes) as total_rx,SUM(responder_txbytes) as total_tx FROM enclaves where responder_role LIKE $role and responder_uid=$service_id group by responder_uid",
{ bind: { role: 'S', service_id:service.id }, type: Sequelize.QueryTypes.SELECT });
if (bytes_total.length) {
    service.dataValues.bytes_total = bytes_total[0];
} else {
    service.dataValues.bytes_total =  { "total_rx": 0 , "total_tx": 0};
fork icon0
star icon0
watch icon1

+ 7 other calls in file

367
368
369
370
371
372
373
374
375
376
  WHERE Quest = ${req.body.questId} AND StepNumber IN (
    SELECT MAX(StepNumber) FROM xenoblade2_guide.questSteps
    WHERE Quest = ${req.body.questId}
    AND ${findStepsInRoute(req.body.lastCompletedStep, req.body.startedRoute)}
  ) AND ${findStepsInRoute(req.body.lastCompletedStep, req.body.startedRoute)}`,
{ type: Sequelize.QueryTypes.SELECT });

if (req.body.lastCompletedStep === lastStep[0].id) {
  await sequelize.query(`
    UPDATE xenoblade2_guide.quests
fork icon0
star icon0
watch icon1

+ 87 other calls in file