Knex Cheat Sheet

From WikiOD

Here is the cheatsheat of Knex and basic guide on how to use Knex

Getting started[edit | edit source]

{: .-three-column}

Connect[edit | edit source]

require('knex')({
  client: 'pg',
  connection: 'postgres://user:pass@localhost:5432/dbname'
})

See: Connect

Create table[edit | edit source]

knex.schema.createTable('user', (table) => {
  table.increments('id')
  table.string('name')
  table.integer('age')
})
.then(() => ···)

See: Schema

Select[edit | edit source]

knex('users')
  .where({ email: 'hi@example.com' })
  .then(rows => ···)

{: data-line=“2”}

See: Select

Insert[edit | edit source]

knex('users')
  .insert({ email: 'hi@example.com' })

{: data-line=“2”}

See: Insert

Update[edit | edit source]

knex('users')
  .where({ id: 135 })
  .update({ email: 'hi@example.com' })

{: data-line=“2,3”}

See: Update

Migrations[edit | edit source]

knex init
knex migrate:make migration_name
knex migrate:make migration_name -x ts # Generates a TypeScript migration file
knex migrate:latest
knex migrate:rollback

See: Migrations

Seeds[edit | edit source]

knex seed:make seed_name
knex seed:make seed_name -x ts # Generates a TypeScript seed file
knex seed:run # Runs all seed files
knex seed:run --specific=seed-filename.js # Runs a specific seed file

See: Seeds

Connect[edit | edit source]

{: .-three-column}

Libraries[edit | edit source]

pg | PostgreSQL |
mysql | MySQL or MariaDB |
sqlite3 | Sqlite3 |
mssql | MSSQL |

Install any of these packages along with knex.

See: Node.js installation

Connect via host[edit | edit source]

var knex = require('knex')({
  client: 'mysql',
  connection: {
    host: '127.0.0.1',
    user: 'your_database_user',
    password: 'your_database_password',
    database: 'myapp_test'
  },
  pool: { min: 0, max: 7 }
})

{: data-line=“2,3”}

See: Initializing the library

Connect via URL[edit | edit source]

var pg = require('knex')({
  client: 'pg',
  connection: process.env.DATABASE_URL,
  searchPath: 'knex,public',
  pool: { min: 0, max: 7 }
})

{: data-line=“2,3”}

Connect via Sqlite[edit | edit source]

var knex = require('knex')({
  client: 'sqlite3',
  connection: { filename: './mydb.sqlite' }
})

{: data-line=“2,3”}

Select[edit | edit source]

Where[edit | edit source]

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

Where[edit | edit source]

  .where('title', 'Hello')
  .where({ title: 'Hello' })
  .whereIn('id', [1, 2, 3])
  .whereNot(···)
  .whereNotIn('id', [1, 2, 3])

Where conditions[edit | edit source]

  .whereNull('updated_at')
  .whereNotNull(···)
  .whereExists('updated_at')
  .whereNotExists(···)
  .whereBetween('votes', [1, 100])
  .whereNotBetween(···)
  .whereRaw('id = ?', [1])

Where grouping[edit | edit source]

  .where(function () {
    this
      .where('id', 1)
      .orWhere('id', '>', 10)
  })

See: Where clauses

Join[edit | edit source]

knex('users')

Basic join[edit | edit source]

  .join('contacts', 'users.id', '=', 'contacts.id')
  .join('contacts', {'users.id': 'contacts.id'})

Strings[edit | edit source]

  .join('accounts', 'accounts.type', '=', knex.raw('?', ['admin']))

Directions[edit | edit source]

  .leftJoin(···)
  .leftOuterJoin(···)
  .rightJoin(···)
  .rightOuterJoin(···)
  .outerJoin(···)
  .fullOuterJoin(···)
  .crossJoin(···)

Raw[edit | edit source]

  .joinRaw('natural full join table1')

Grouping[edit | edit source]

  .join('accounts', function () {
    this
      .on('accounts.id', '=', 'users.account_id')
      .orOn('accounts.owner_id', '=', 'users.id')

      .onIn('accounts.id', [1, 2, 3, 5, 8])
      .onNotIn(···)

      .onNull('accounts.email')
      .onNotNull(···)

      .onExists(function () {
        this.select(···)
      })
      .onNotExists(···)
  })

See: Join methods

Others[edit | edit source]

knex('users')
  .distinct()

Group[edit | edit source]

  .groupBy('count')
  .groupByRaw('year WITH ROLLUP')

Order[edit | edit source]

  .orderBy('name', 'desc')
  .orderByRaw('name DESC')

Offset/limit[edit | edit source]

  .offset(10)
  .limit(20)

Having[edit | edit source]

  .having('count', '>', 100)
  .havingIn('count', [1, 100])

Union[edit | edit source]

  .union(function() {
    this.select(···)
  })
  .unionAll(···)

See: Query builder

Etc[edit | edit source]

knex('users')
  .pluck('id')
  .then(ids => { ··· })
knex('users')
  .first()
  .then(user => { ··· })

Booleans[edit | edit source]

  .count('active')
  .count('active as is_active')

Numbers[edit | edit source]

  .min('age')
  .max('age')
  .sum('age')
  .sumDistinct('age')
  .avg('age')

See: Query builder

Schema[edit | edit source]

Create table[edit | edit source]

knex.schema.createTable('accounts', table => {

Columns[edit | edit source]

  table.increments('id')
  table.string('account_name')
  table.integer('age')
  table.float('age')
  table.decimal('balance', 8, 2)
  table.boolean('is_admin')
  table.date('birthday')
  table.time('created_at')
  table.timestamp('created_at').defaultTo(knex.fn.now())
  table.json('profile')
  table.jsonb('profile')
  table.uuid('id').primary()

Constraints[edit | edit source]

  table.unique('email')
  table.unique(['email', 'company_id'])
  table.dropUnique(···)

Indices[edit | edit source]

  table.foreign('company_id')
    .references('companies.id')
  table.dropForeign(···)

Variations[edit | edit source]

  table.integer('user_id')
    .unsigned()
    .references('users.id')
})
.then(() => ···)

{: .-setup}

See: Schema builder

Alter table[edit | edit source]

knex.schema.table('accounts', table => {

Create[edit | edit source]

  table.string('first_name')

Alter[edit | edit source]

  table.string('first_name').alter()
  table.renameColumn('admin', 'is_admin')

Drop[edit | edit source]

  table.dropColumn('admin')
  table.dropTimestamps('created_at')
})

{: .-setup}

See: Schema builder

Other methods[edit | edit source]

knex.schema
  .renameTable('persons', 'people')
  .dropTable('persons')
  .hasTable('users').then(exists => ···)
  .hasColumn('users', 'id').then(exists => ···)

See: Schema builder

Modifying[edit | edit source]

{: .-three-column}

Insert[edit | edit source]

knex('users')

Insert one[edit | edit source]

  .insert({ name: 'John' })

Insert many[edit | edit source]

  .insert([
    { name: 'Starsky' },
    { name: 'Hutch' }
  ])

See: Insert

Update[edit | edit source]

knex('users')
  .where({ id: 2 })
  .update({ name: 'Homer' })

See: Update

Delete[edit | edit source]

knex('users')
  .where({ id: 2 })
  .del()

See: Delete

Migrations[edit | edit source]

Setting up[edit | edit source]

Create knexfile.js[edit | edit source]

./node_modules/.bin/knex init

Create a migration[edit | edit source]

knex migrate:make migration_name
knex migrate:make migration_name --env production

Run migrations[edit | edit source]

knex migrate:latest
knex migrate:latest --env production

Rollback[edit | edit source]

knex migrate:rollback
knex migrate:rollback --env production

See: Migrations

Credit:rstacruz