Cheat Sheet速查表
跳转到主要内容

Knex 速查表

本文根据 Devhints / Knex 翻译。代码示例及版本范围沿用原文。原文标注更新日期:2020-06-03。

Knex 这是一个用于 Node.js 的 SQL 查询构建器。本指南针对的是 v0.13.0。

入门

连接

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

参见: 连接

创建表

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

参见: Schema(模式)

查询 (Select)

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

参见: 查询 (Select)

插入 (Insert)

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

参见: 插入 (Insert)

更新

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

参见: 更新

数据库迁移

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

参见: 数据库迁移

数据填充 (Seeds)

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

参见: 数据填充 (Seeds)

连接

库 (Libraries)

pgPostgreSQL
mysqlMySQL 或 MariaDB
sqlite3Sqlite3
mssqlMSSQL

安装以下任一包,并配合 knex.

参见: Node.js 安装

通过主机连接

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

参见: 初始化库

通过 URL 连接

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

通过 Sqlite 连接

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

查询 (Select)

位置

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

位置

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

Where 条件

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

Where 分组

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

参见: Where 子句

连接 (Join)

knex('users')

基本连接

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

字符串

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

方向

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

原生 (Raw)

  .joinRaw('natural full join table1')

分组

  .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(···)
  })

参见: 连接方法

其他

knex('users')
  .distinct()

分组 (Group)

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

排序 (Order)

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

偏移/限制 (Offset/limit)

  .offset(10)
  .limit(20)

Having 子句

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

联合类型

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

参见: 查询构建器 (Query builder)

其他

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

布尔值

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

数字

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

参见: 查询构建器 (Query builder)

Schema(模式)

创建表

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

列 (Columns)

  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)

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

索引 (Indices)

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

变体

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

参见: 模式构建器 (Schema builder)

修改表 (Alter table)

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

创建 (Create)

  table.string('first_name')

修改 (Alter)

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

删除 (Drop)

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

参见: 模式构建器 (Schema builder)

其他方法

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

参见: 模式构建器 (Schema builder)

修改数据

插入 (Insert)

knex('users')

插入单条记录

  .insert({ name: 'John' })

插入多条记录

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

参见: 插入 (Insert)

更新

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

参见: 更新

删除

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

参见: 删除

数据库迁移

设置

创建 knexfile.js

./node_modules/.bin/knex init

创建迁移

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

执行迁移

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

回滚

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

参见: 数据库迁移