How to use knex

Comprehensive knex code examples:

How to use knex.on:

10
11
12
13
14
15
16
17
18
19
20
21
    console.error("Can't connect to DB!")
    throw error
  })


if (process.env.NODE_ENV !== 'production') {
  knex.on('error', (error) => {
    console.log('Error', error)
  })


  knex.on('query', (query) => {

How to use knex.Client:

How to use knex.ref:

34
35
36
37
38
39
40
41
42
43

//const data = await knex.select('id as identifier').from('users');
//const data = await knex.select(knex.ref('id').as('identifier')).from('users');

// const data = await knex
//   .select(knex.ref('id'), knex.ref('login'))
//   .from('users');
// const data = await knex
//   .select(knex.ref('id').as('identifier'))
//   .select(knex.ref('login').as('name'))

How to use knex.min:

44
45
46
47
48
49
50
51
52
53
//   .from('users');

//const data = await knex.sum('age').from('users2');
//const data = await knex.avg('age').from('users2');
//const data = await knex.max('age').from('users2');
//const data = await knex.min('age').from('users2');

// const data = await knex.avg('sum_age').from(function () {
//   this.sum('age as sum_age').from('users2').groupBy('name').as('t1');
// });

How to use knex.max:

43
44
45
46
47
48
49
50
51
52
//   .select(knex.ref('login').as('name'))
//   .from('users');

//const data = await knex.sum('age').from('users2');
//const data = await knex.avg('age').from('users2');
//const data = await knex.max('age').from('users2');
//const data = await knex.min('age').from('users2');

// const data = await knex.avg('sum_age').from(function () {
//   this.sum('age as sum_age').from('users2').groupBy('name').as('t1');

How to use knex.sum:

41
42
43
44
45
46
47
48
49
// const data = await knex
//   .select(knex.ref('id').as('identifier'))
//   .select(knex.ref('login').as('name'))
//   .from('users');

//const data = await knex.sum('age').from('users2');
//const data = await knex.avg('age').from('users2');
//const data = await knex.max('age').from('users2');
//const data = await knex.min('age').from('users2');

How to use knex.seed:

48
49
50
51
52
53
54
55
56
57
58
requireDir('core', { recurse: true });
requireDir('usercases', { recurse: true });


function cleanDBAndFlushCache(done) {
  logger.info('Cleaning the test DB after each test...');
  knex.seed.run()
    .then(function () {
      client.flushdb(done);
    })
    .catch(function(err) {

How to use knex.column:

67
68
69
70
71
72
73
74
75

// const subquery = knex.select('name', 'age').from('users2').as('u');
// const data = await knex.select('u.name', 'u.age').from(subquery);

//const data = await knex.column('id', 'name', 'age').select().from('users2');
//const data = await knex.column(['id', 'name', 'age']).from('users2');
// const data = await knex
//   .column('id as identifier', { by: 'name' }, 'age')
//   .from('users2');

How to use knex.transactionProvider:

61
62
63
64
65
66
67
68
69
70
```js
const knex = require('knex')({ ...config })

async function getLogsValue() {
  try {
    const trxProvider = knex.transactionProvider();
    const trx = await trxProvider();
    const logs = await trx('tableName').select();
    return logs;
  } catch (error) {

How to use knex.js:

8
9
10
11
12
13
14
15
16
17
Knex.js는 다양한 DBMS(**Postgres, MSSQL, MySQL, MariaDB, SQLite3, Oracle, and Amazon Redshift**)를 지원하고 있고 단순 Query 생성 뿐만 아니라 **schema builder, transaction, connection pooling** 등의 기능도 지원하고 있다. 자세한 내용은 [공식홈페이지](http://knexjs.org)를 살펴보자.

우선 프로젝트에 `npm install knex —save` 로 knex 모듈을 추가하고 다음과 같이 DB에 연결한다. 

```jsx
// knex.js

const knex = require('knex')({
    client: 'mysql2',
    connection: {

How to use knex.queryBuilder:

198
199
200
201
202
203
204
205
206
207
// const createMedia = {
//     media:      request.body.recordObject.media,
//     sortID:     newSortID
//   };

db.queryBuilder()
  .from(tableName)
  .max("sortID")
  .first() // * Add this to get an object. -- 05/06/2021 MF
  .then((maxSortID) => {

How to use knex.avg:

42
43
44
45
46
47
48
49
50
51
//   .select(knex.ref('id').as('identifier'))
//   .select(knex.ref('login').as('name'))
//   .from('users');

//const data = await knex.sum('age').from('users2');
//const data = await knex.avg('age').from('users2');
//const data = await knex.max('age').from('users2');
//const data = await knex.min('age').from('users2');

// const data = await knex.avg('sum_age').from(function () {

How to use knex.migrate:

27
28
29
30
31
32
33
34
35
36
before(function(done) {
  logger.fatal('Setting up the test DB before running tests...');
  knex.migrate.rollback()
    .then(function() {
      logger.fatal('Migrate latest DB schema...');
      return knex.migrate.latest();
    })
    .then(function () {
      logger.fatal('Creating DB seeds...');
      return knex.seed.run();

How to use knex.knex:

30
31
32
33
34
35
36
37
38
39
  connection || process.env.CONNECT_TO || process.env.DATABASE_URL || process.env.KNEX_URI;

if (!knexConnection) {
  throw new Error(`No Knex connection URI specified.`);
}
this.knex = knex({
  client: this.client,
  connection: knexConnection,
  ...knexOptions,
});

How to use knex.table:

800
801
802
803
804
805
806
807
808
809
// //select * from "users" inner join "accounts" on "accounts"."type" = "admin"

//const data = await knex.from('users').innerJoin('accounts','users.id','accounts.user_id');
//select * from "users" inner join "accounts" on "users"."id" = "accounts"."user_id"

// const data = await knex.table('users').innerJoin('accounts', 'users.id', '=', 'accounts.user_id');
// //select * from "users" inner join "accounts" on "users"."id" = "accounts"."user_id"

// const data = await knex('users').innerJoin('accounts',  (qb) => {
//   qb.on('accounts.id', '=', 'users.account_id')

How to use knex.QueryBuilder:

30
31
32
33
34
35
36
37
38
39
/* QueryBuilder Extension */
const Knex = require('knex');
const QueryBuilder = require('knex/lib/query/querybuilder');

try {
  Knex.QueryBuilder.extend('whereInArray', function (column, values) {
    return this.where(column, knex.raw('any(?)', [values]));
  });
} catch (e) {
  if (e.message !== "Can't extend QueryBuilder with existing method ('whereInArray').") {

How to use knex.withSchema:

97
98
99
100
101
102
103
104
105
106
107


//getting cinemaid by cinema name
router.get('/getcinemaidbyname/:cinemaname', async (req, res) => {
  try {
    console.log('sending cinema id by cinema name');
    const result = await knex.withSchema('bookmyshow').table('cinemas').where('name', req.params.cinemaname);
    res.json({ result: result[0].id });
  }
  catch (error) {
    console.log(error);

How to use knex.delete:

95
96
97
98
99
100
101
102
103
104
 * This generally shouldn't be used in favour of `bot.database.leaveServer`
 * @param {ServerID} serverID The server's Snowflake ID
 * @returns {Promise<Array>}
 */
deleteServer: function deleteServer(serverID) {
    return knex.delete()
        .from(SERVERS_TABLE)
        .where({
            server: serverID
        });

How to use knex.schema:

29
30
31
32
33
34
35
36
37
38
await knex('test_table').truncate()

console.log('See Transaction...')
await knex.transaction(async trx => {  
  await knex('test_table').insert({ name: 'aa' }).transacting(trx)
  // await knex.schema.raw('SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;')
  let rv = await knex.select().from('test_table')
  console.log(rv)

  await knex('test_table').insert({ name: 'bb' }).transacting(trx)

How to use knex.transaction:

27
28
29
30
31
32
33
34
35
36

// empty data
await knex('test_table').truncate()

console.log('See Transaction...')
await knex.transaction(async trx => {  
  await knex('test_table').insert({ name: 'aa' }).transacting(trx)
  // await knex.schema.raw('SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;')
  let rv = await knex.select().from('test_table')
  console.log(rv)

How to use knex.insert:

77
78
79
80
81
82
83
84
85
86
 * @param webhookID
 * @param webhookToken
 * @returns {Promise<Array>}
 */
addServer: function addNewServer(server, addedBy, name, timestamp, language = "en-gb", webhookID, webhookToken) {
    return knex.insert({
        server,
        owner: addedBy,
        name,
        prefix: "!",

How to use knex.destroy:

76
77
78
79
80
81
82
83
84
85
86
87
88


  const data = await knex.select().from('users2').offset(1).limit(2);
  //.toSQL().sql;


  console.log(data);
  knex.destroy();
}


async function createTable() {
  // await knex.schema.createTable('users2', (table) => {

How to use knex.raw:

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);

How to use knex.select:

30
31
32
33
34
35
36
37
38
39

console.log('See Transaction...')
await knex.transaction(async trx => {  
  await knex('test_table').insert({ name: 'aa' }).transacting(trx)
  // await knex.schema.raw('SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;')
  let rv = await knex.select().from('test_table')
  console.log(rv)

  await knex('test_table').insert({ name: 'bb' }).transacting(trx)
  await knex.schema.raw('SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;')

How to use knex.from:

34
35
36
37
38
39
40
41
42
  }
}

static async getUrls() {

  const selectNullableData = await knex.from('urls').select('external_urls',).where('robot_tag', null)
    .orderBy('id');

  return selectNullableData;