How to use the raw function from knex

Find comprehensive JavaScript knex.raw code examples handpicked from public code repositorys.

82
83
84
85
86
87
88
89
90
91
return knex.insert({
    server,
    owner: addedBy,
    name,
    prefix: "!",
    timestamp: knex.raw(`FROM_UNIXTIME(${(timestamp ? new Date(timestamp).getTime() : new Date().getTime()) / 1000})`),
    language,
    webhookID,
    webhookToken
}).into(SERVERS_TABLE);
fork icon7
star icon35
watch icon0

+ 26 other calls in file

407
408
409
410
411
412
413
414
415
    .limit(limit || total)
    .offset(offset || 0);

// .select([
//     ...COLLECTION_JOINED_FIELDS,
//     db.raw(`ARRAY_AGG(DISTINCT ${USER_COLLECTIONS_DATASOURCES_TABLE}."dataSourceId") as "dataSources"`),
//     db.raw(`COALESCE(ARRAY_AGG(DISTINCT ${USER_SHARED_COLLECTIONS_TABLE}."userId")
//         FILTER (WHERE ${USER_SHARED_COLLECTIONS_TABLE}."userId" IS NOT NULL)) as "users"`),
// ])
fork icon3
star icon5
watch icon0

58
59
60
61
62
63
64
65
66
67
            }
        }
    }
)
.then(function() {
    return knex.raw("select * from school where sid = ?", req.params.sid) })
.then(function(results) {
    
    res.render('addroom', {results: results.rows, alert : "Room added successfully. ", showButtons: true, user: user} );
});
fork icon1
star icon0
watch icon0

+ 41 other calls in file

63
64
65
66
67
68
69
70
71
72
73
exports.schoolview = (req, res) => {
    const user = req.session.user


    knex.raw("select * from school where sid = ?", req.params.sid).then(function (schools) {
        knex.raw("select * from room, school where room.sid = school.sid and room.sid = ?", req.params.sid).then(function (rooms) {
            knex.raw("select count(*) from room, school where room.sid = school.sid and room.sid = ?", req.params.sid).then(function (count) {
                knex.raw("update school set numrooms = (select count(*) from room, school where room.sid = school.sid and room.sid = ?) where school.sid = ?", [req.params.sid, req.params.sid])
                    .then(function (result) {
                        
                        res.render('viewschool', { results: schools.rows, rooms: rooms.rows, count: count.rows, showButtons : true, user: user });
fork icon1
star icon0
watch icon0

+ 4 other calls in file

19
20
21
22
23
24
25
26
27
28
29
30
31
32


knex.column('title', 'author', 'year').select().from('books');


knex.select('*').from('users');


knex.with('with_alias', knex.raw('select * from "books" where "author" = ?', 'Test')).select('*').from('with_alias');


knex.withRecursive('ancestors', (qb) => {
    qb.select('*').from('people').where('people.id', 1).union((qb) => {
      qb.select('*').from('people').join('ancestors', 'ancestors.parentId', 'people.id')
fork icon0
star icon2
watch icon0

+ 2 other calls in file

180
181
182
183
184
185
186
187
188
189


static async getCrawledLinksCountById(userId) {
  const crawledTodayCount = await knex('links').count()
    .where('updated_at', '<', knex.raw('NOW() - INTERVAL \'1 DAY\''))
    .orWhere('created_at', '<', knex.raw('NOW() - INTERVAL \'1 DAY\''))
    .whereNotNull('changeing').where('user_id', '=', userId);

  return { crawledTodayLinksCount: Number(crawledTodayCount[0].count) };
}
fork icon0
star icon0
watch icon1

+ 9 other calls in file

271
272
273
274
275
276
277
278
279
280
//   // .where(knex.raw('age <> ?', [40]))
//   // .andWhere(knex.raw('age <> ?', [20]))
//   .groupBy('age');

// const data = await knex('users2').where(
//   knex.raw(':name: = :thisGuy or :name: = :otherGuy', {
//     name: 'users2.name',
//     thisGuy: 'Bob',
//     otherGuy: 'Ricky',
//   })
fork icon0
star icon0
watch icon1

+ 32 other calls in file

89
90
91
92
93
94
95
96
97
98
99
// }


async function insertUsersData() {
  const datas = require("./MOCK_DATA.json");
  try {
    await knex.raw(Table("users").create(datas));
    console.log("users data inserted");
  } catch (error) {
    console.error(error);
  } finally {
fork icon0
star icon0
watch icon0

+ 8 other calls in file

39
40
41
42
43
44
45
46
47
48
49
50
51
 ******************************/
router.get("/", (request, response) => {


  let sqlQuery = "SELECT * FROM amazon INNER JOIN (SELECT ASIN, GROUP_CONCAT(searchIndex) AS searchIndex FROM (SELECT DISTINCT ASIN, searchIndex FROM amazonImport WHERE searchIndex IS NOT NULL ORDER BY searchIndex) AS searchIndexDistinct GROUP BY ASIN) AS amazonSearchIndex ON amazon.ASIN = amazonSearchIndex.ASIN WHERE active = 1 AND merchant = 'Amazon' ORDER BY viewed, createDate, authorName, titleName";


  // db.raw(sqlQuery).toSQL();


  // db.select(select)
  //   .from(tableName)
  //   // .limit(limit)
fork icon0
star icon0
watch icon1

+ 19 other calls in file

124
125
126
127
128
129
130
131
132
133
134
135




router.get('/get-states-and-cities', async (req, res) => {
  try {
    console.log('getting states and cities');
    // knex.raw('json_agg(cities.*) as cities')   -> if we want the full data of 2nd table 
    // knex.raw('json_agg(json_build_object(\'id\', cities.id, \'name\', cities.name))  ->if we want some fields of 2nd table data
    await knex.select('states.*', knex.raw('json_agg(json_build_object(\'id\', cities.id, \'name\', cities.name)) as cities'))
      .withSchema('bookmyshow')
      .table('states')
fork icon0
star icon0
watch icon0