Knex Query Builder 完全指南:从标识符语法到查询编译的 API 深度剖析

原创2026-09-19 15:32:371,832 阅读
文章标签:数据库后端关系型数据库

Knex Query Builder 完全指南:从标识符语法到查询编译的 API 深度剖析

Knex 的 Query Builder(查询构建器)是整库的核心,它提供了构建与执行 select、insert、update、delete 等标准 SQL 查询的统一链式接口。本指南以 docs/src/guide/query-builder.md 为骨架,逐方法讲解标识符语法、通用方法、Where 子句、Join、OnClause、ClearClause 与 Having 的完整用法,并结合 lib/query/querybuilder.js 的源码实现,带你掌握从"写出一条链式查询"到"理解它如何被编译成 SQL"的完整链路,可直接对照使用在基于 PostgreSQL、MySQL、CockroachDB、SQL Server、SQLite3 与 Oracle 的任何项目中。

一、Query Builder 在 Knex 中的定位

在源码层面,查询构建器由 lib/query/querybuilder.js 中的 Builder 类实现。从源码结构看,Builder 继承自 EventEmitter,构造函数中初始化了 _single(单值配置,如表名、超时)、_statements(语句数组,如 where、join 的累积)、_method = 'select'(当前查询类型)以及 _joinFlag = 'inner'、_boolFlag = 'and' 等内部标志(见 lib/query/querybuilder.js)。所有链式调用最终通过 toSQL() 交给 client.queryCompiler(this) 编译成目标方言的 SQL 字符串(见 lib/query/querybuilder.js)。

二、标识符(Identifier)语法

在 API 的许多位置,表名或列名这类标识符都可以作为参数传入。最常见的是直接写 tableName.columnName、tableName 或 columnName;当需要在查询后续环节以别名引用该标识符时,有两种声明方式:

  1. 直接追加 as aliasName 后缀:identifierName as aliasName
  2. 传入对象:{ aliasName: 'identifierName' }

当对象包含多个别名(如 { alias1: 'identifier1', alias2: 'identifier2' })时,所有被别名的标识符会展开为逗号分隔的列表。

knex({ a: 'table', b: 'table' })
  .select({
    aTitle: 'a.title',
    bTitle: 'b.title',
  })
  .whereRaw('?? = ??', ['a.column_1', 'b.column_2']);

::: info 注意 schema 不能写进标识符 标识符语法中没有声明 schema 的位置,如果你直接写 schemaName.tableName,查询可能被错误渲染。请改用 .withSchema('schemaName')。 :::

三、Common:查询构建的核心方法

3.1 knex:链的起点

knex(tableName, options) / knex.[methodName]

查询构建器要么通过指定要查询的 tableName 启动,要么直接在 knex 对象上调用方法启动。这会开启一条类似 jQuery 的链式调用,你可以不断追加查询构建方法,最终调用任意接口方法将查询 toString() 转换,或用 promise、callback、stream 执行。

TypeScript 用法:可把数据库行的类型作为类型参数传入,以获得整条链上的自动补全:

interface User {
  id: number;
  name: string;
  age: number;
}

knex('users').where('id').first(); // Resolves to any

knex<User>('users') // User 是数据库中行的类型
  .where('id', 1) // IDE 可以辅助补全 id
  .first(); // Resolves to User | undefined

纯 JavaScript 中也可以通过 JSDoc 泛型注释获得同样效果:

/**
 * @typedef {Object} User
 * @property {number} id
 * @property {number} age
 * @property {string} name
 *
 * @returns {Knex.QueryBuilder<User, {}>}
 */
const Users = () => knex('Users');

// 'id' 属性可以被编辑器自动补全
Users().where('id', 1);

可变流式 API 与类型推断的注意点:knex 的大部分 API 会原地修改当前对象并返回它,这种模式对类型推断不友好。例如在一个已声明变量上追加 .select('age') 不会改变该变量的类型;推荐的做法是让链上的"最后一个值"决定类型,并将任何后续链式续接的结果赋给一个独立的新变量。也可以显式通过第二个类型参数指定结果类型:knex<User, Pick<User, 'id' | 'age'>>('users'),但需要注意 TypeScript 无法约束"这些属性确实被 select 了",因此 queryBuilder.select('name') 依然能通过编译,只是运行时结果与声明类型不符。

3.2 only:只查父表(仅 PostgreSQL)

knex(tableName, { only: true }) 或 .from(tableName, { only: true })

only: true 时,Knex 会在表名前加 ONLY 关键字,告诉 PostgreSQL 只读取该命名表的行,排除从子表继承的行。这在使用了表继承、想避免拉入后代数据时很有用。目前仅 PostgreSQL 支持。

knex('users', { only: true }).select('*');
knex.select('*').from('users', { only: true });

3.3 timeout:查询超时

.timeout(ms, options={ cancel: boolean })

为查询设置超时,超时后抛出 TimeoutError。默认不会在数据库层面取消查询。抛出的错误包含查询、绑定值与所设超时的信息,适合用于确保复杂查询不会执行过久。传入 { cancel: true } 会在达到超时值时从数据库层面取消查询——该选项目前仅 MySQL 和 PostgreSQL 支持。

从源码看,timeout(ms, { cancel } = {}) 只在 ms 是正数时写入 this._timeout,并且只有在传 cancel: true 时才调用 this.client.assertCanCancelQuery() 校验当前方言支持取消(见 lib/query/querybuilder.js)。

knex.select().from('books').timeout(1000);
knex.select().from('books').timeout(1000, {
  cancel: true, // 仅 MySQL 和 PostgreSQL
});

3.4 select / as / column / from / fromRaw

.select([*columns]):创建 select 查询,接受可选的列数组,未指定时默认 *,结果以对象数组形式返回。

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

select 的 TypeScript 类型推断:只要 select 参数与记录类型的键名完全一致,就能推断出结果类型;但别名和限定名会阻碍推断。例如 knex.select('id').from<User>('users') 推断为 Pick<User, "id">[],而 knex.select('users.id') 会回退到 any[]。此时可以借助 knex.ref 绕过:knex.select(knex.ref('id').withSchema('users')).from<User>('users') 仍能推断为 Pick<User, "id">[],knex.select(knex.ref('id').as('identifier')).from<User>('users') 则推断为 { identifier: number; }[]。

.as(name):为子查询起别名;如果不是子查询会被忽略。

knex
  .avg('sum_column1')
  .from(function () {
    this.sum('column1 as sum_column1').from('t1').groupBy('column1').as('t1');
  })
  .as('ignored_alias');

.column(columns):显式指定 select 查询要选的列,接受数组、对象或列名列表。传对象会自动用键作为列的别名。select 在源码中就是 columns 的别名(Builder.prototype.select = Builder.prototype.columns,见 lib/query/querybuilder.js)。

knex.column('title', 'author', 'year').select().from('books');
knex.column(['title', 'author', 'year']).select().from('books');
knex.column('title', { by: 'author' }, 'year').select().from('books');

.from([tableName], options={only: boolean}):指定当前查询使用的表,会替换已指定的表名,常用于高级 where 或 union 中的子查询。only 选项同上,仅 PostgreSQL 支持。

knex.select('*').from('users');
knex.select('id').from<User>('users'); // Resolves to Pick<User, "id">[]

.fromRaw(sql, [bindings]):直接以原始 SQL 作为数据源。

knex.select('*').fromRaw('(select * from "users" where "age" > ?)', '18');

3.5 with 系列:CTE(公共表表达式)

.with(alias, [columns], callback|builder|raw):为查询添加 "with" 子句。PostgreSQL、Oracle、SQLite3 和 MSSQL 支持。可选列名列表需在别名后提供,且至少包含一列。

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

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

knex
  .with('with_alias', (qb) => {
    qb.select('*').from('books').where('author', 'Test');
  })
  .select('*')
  .from('with_alias');

.withRecursive(alias, [columns], callback|builder|raw):与 with 相同,只是追加 "recursive" 以支持自引用 CTE。注意 Oracle 等数据库在使用 rCTE 时必须提供列名列表;使用 union/unionAll 时两个分支须返回相同列与类型,递归分支中若引入了 join 应避免 select('*')。

knex
  .withRecursive('ancestors', (qb) => {
    qb.select('people.*')
      .from('people')
      .where('people.id', 1)
      .unionAll((qb) => {
        qb.select('people.*')
          .from('people')
          .join('ancestors', 'ancestors.parentId', 'people.id');
      });
  })
  .select('*')
  .from('ancestors');

knex
  .withRecursive('family', ['name', 'parentName'], (qb) => {
    qb.select('name', 'parentName')
      .from('folks')
      .where({ name: 'grandchild' })
      .unionAll((qb) =>
        qb
          .select('folks.name', 'folks.parentName')
          .from('folks')
          .join('family', knex.ref('family.parentName'), knex.ref('folks.name'))
      );
  })
  .select('name')
  .from('family');

.withMaterialized(alias, [columns], callback|builder|raw) 与 .withNotMaterialized(alias, [columns], callback|builder|raw):分别添加物化/非物化的 with 子句,PostgreSQL 和 SQLite3 支持,可选列名列表需至少包含一列。调用方式与 with 完全一致。

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

knex
  .withNotMaterialized('with_alias', (qb) => {
    qb.select('*').from('books').where('author', 'Test');
  })
  .select('*')
  .from('with_alias');

3.6 withSchema

.withSchema([schemaName]):指定作为表名前缀的 schema。

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

3.7 JSON 操作函数族

.jsonExtract(column|builder|raw|array[], path, [alias], [singleValue]):按 JsonPath 从 json 列中提取值,可指定别名。singleValue 用于 Oracle/MSSQL 声明返回的是单值还是数组/对象。传二维数组可一次完成多次提取。

knex('accounts').jsonExtract('json_col', '$.name');
knex('accounts').jsonExtract('json_col', '$.name', 'accountName');
knex('accounts').jsonExtract('json_col', '$.name', 'accountName', true);
knex('accounts').jsonExtract([
  ['json_col', '$.name', 'accountName'],
  ['json_col', '$.lastName', 'accountLastName'],
]);

所有 json*() 函数都可以直接从 knex 对象调用,并且可以互相嵌套:

knex('cities').jsonExtract([
  [knex.jsonRemove('population', '$.min'), '$', 'withoutMin'],
  [knex.jsonRemove('population', '$.max'), '$', 'withoutMax'],
  [knex.jsonSet('population', '$.current', '1234'), '$', 'currentModified'],
]);

.jsonSet(column|builder|raw, path, value, [alias]):返回在指定 JsonPath 处设置值后的 json 值/对象/数组。值可以是单值或 json 对象;若该位置已存在值则被替换。Redshift 及 Oracle 21c 之前的版本不支持。

knex('accounts').jsonSet('json_col', '$.name', 'newName', 'newNameCol');
knex('accounts').jsonSet('json_col', '$.name', { name: 'newName' }, 'newNameCol');

.jsonInsert(column|builder|raw, path, value, [alias]):返回在指定 JsonPath 处插入值后的 json 值/对象/数组。与 jsonSet 不同,若该路径已有值则不会被替换。Redshift 及 Oracle 21c 之前的版本不支持。第一个参数也可以是其他 json 函数的返回值(如嵌套的 jsonExtract)。

knex('accounts').jsonInsert('json_col', '$.name', 'newName', 'newNameCol');
knex('accounts').jsonInsert('json_col', '$.name', { name: 'newName' }, 'newNameCol');
knex('accounts').jsonInsert(
  knex.jsonExtract('json_col', '$.otherAccount'),
  '$.name',
  { name: 'newName' },
  'newNameCol'
);

.jsonRemove(column|builder|raw, path, [alias]):返回在指定 JsonPath 处移除值后的 json 值/对象/数组。Redshift 及 Oracle 21c 之前的版本不支持。

knex('accounts').jsonRemove('json_col', '$.name', 'colWithRemove');

3.8 offset / limit

.offset(value, options={skipBinding: boolean}):为查询添加 offset 子句。可选的 skipBinding 参数可避免把 offset 作为预编译参数值(部分数据库不允许 offset 使用占位符)。

knex.select('*').from('users').offset(10);
knex.select('*').from('users').offset(10).toSQL().sql;
// offset 值不作为预编译参数
knex.select('*').from('users').offset(10, { skipBinding: true }).toSQL().sql;

.limit(value, options={skipBinding: boolean}):为查询添加 limit 子句,skipBinding 语义同上。

重要安全行为:Knex 在查询"不健全"时会在 SQL 编译阶段抛错,以防止意外数据丢失或意外行为。当 "delete" 或 "truncate" 语句上出现 "limit" 子句时会抛错,例如以下查询都会抛错:

knex('accounts').limit(10).del().toSQL();
knex('logs').limit(10).truncate().toSQL();
knex.select('*').from('users').limit(10).offset(30);
knex.select('*').from('users').limit(10).offset(30).toSQL().sql;
// limit 值不作为预编译参数
knex
  .select('*')
  .from('users')
  .limit(10, { skipBinding: true })
  .offset(30)
  .toSQL().sql;

3.9 union / unionAll / intersect / except

.union([*queries], [wrap]):创建 union 查询,接受回调、builder 或 raw 语句组成的数组或列表,可选布尔 wrap 为 true 时各查询会被单独包在括号里。

knex
  .select('*')
  .from('users')
  .whereNull('last_name')
  .union(function () {
    this.select('*').from('users').whereNull('first_name');
  });

knex
  .select('*')
  .from('users')
  .whereNull('last_name')
  .union([knex.select('*').from('users').whereNull('first_name')]);

knex
  .select('*')
  .from('users')
  .whereNull('last_name')
  .union(
    knex.raw('select * from users where first_name is null'),
    knex.raw('select * from users where email is null')
  );

注意:如果要对 union 的各个输入分别应用 orderBy、groupBy、limit、offset 或 having,必须以 knex.union 作为基础语句;否则这些子句会被追加到整个 union 的末尾:

// 反例:子句被追加到查询末尾
knex('users')
  .select('id', 'name')
  .groupBy('id')
  .union(knex('invitations').select('id', 'name').orderBy('expires_at'));

// 正例:以 knex.union 为基座
knex.union([
  knex('users').select('id', 'name').groupBy('id'),
  knex('invitations').select('id', 'name').orderBy('expires_at'),
]);

.unionAll([*queries], [wrap]):创建 union all 查询,签名与 union 相同,wrap: true 时各查询单独加括号。示例与 union 完全对应。

.intersect([*queries], [wrap]):创建 intersect 查询,签名与 union 相同,wrap: true 时各查询单独加括号。MySQL 不支持 intersect。

.except([*queries], [wrap]):创建 except 查询,签名与 union 相同,wrap: true 时各查询单独加括号。MySQL 不支持 except。

3.10 insert

.insert(data, [returning], [options]):创建 insert 查询,接受要插入的行属性哈希,或一组 insert 组成的数组(作为单条 insert 命令执行)。若传入 returning 数组(如 ['id', 'title']),promise/回调会以包含指定列的"所有新增行"数组兑现,它是 returning 方法 的快捷方式。

// 在 "mysql"、"sqlite"、"oracle" 中返回 [1];在 "postgresql" 中返回 []
// 除非设置了 'returning' 参数。
knex('books').insert({ title: 'Slaughterhouse Five' });

// 多行插入时空键会被规范化:
knex('coords').insert([{ x: 20 }, { y: 30 }, { x: 10, y: 20 }]);

// "mysql"、"sqlite" 返回 [2];"postgresql" 返回 [2, 3]
knex.insert([{ title: 'Great Gatsby' }, { title: 'Fahrenheit 451' }], ['id']).into('books');

MSSQL 触发器场景:MSSQL 表上的触发器会中断标准 insert 语句返回有效值,可以加 includeTriggerModifications 选项解决(仅在 MSSQL、指定了 returning 值且设置了该选项时才修改 SQL):

knex('books').insert({ title: 'Alice in Wonderland' }, ['id'], {
  includeTriggerModifications: true,
});

useNullAsDefault 配置:若希望未定义的键用 NULL 替换而不是 DEFAULT,可以在 knex 配置中给出 useNullAsDefault:

const knex = require('knex')({
  client: 'mysql',
  connection: {
    host: '127.0.0.1',
    port: 3306,
    user: 'your_database_user',
    password: 'your_database_password',
    database: 'myapp_test',
  },
  useNullAsDefault: true,
});

knex('coords').insert([{ x: 20 }, { y: 30 }, { x: 10, y: 20 }]);

上面这条会被编译为:

insert into `coords` (`x`, `y`) values (20, NULL), (NULL, 30), (10, 20)

3.11 onConflict:冲突处理(PostgreSQL / MySQL / SQLite)

insert(..).onConflict(column) / insert(..).onConflict([column1, column2, ...]) / insert(..).onConflict(knex.raw(...))

当表在某列(或某组列)上有 PRIMARY KEY 或 UNIQUE 索引,而插入行在这些列上的值与已存在行相同时即发生冲突。默认行为是报错并中止查询。通过该方法可改为静默忽略(.onConflict().ignore())或更新已存在行(.onConflict().merge(),即 UPSERT)。

从源码结构看,onConflict(columns) 返回一个专用的 OnConflictBuilder 子构建器,它把冲突列写入 this.builder._single.onConflict,并且必须在后面紧跟 .merge() 或 .ignore(),否则会抛出 "Incomplete onConflict clause" 错误(见 lib/query/querybuilder.js)。

::: info 冲突列的要求 对 PostgreSQL 和 SQLite,指定的列必须是表的主键或具有 UNIQUE 索引,否则查询会执行失败;指定多列时须是复合主键或复合 UNIQUE 索引。MySQL 会忽略指定列、始终使用表的主键。为了在 PostgreSQL、MySQL、SQLite 间可移植,必须同时在 .onConflict() 中显式指定列,且这些列必须是表的主键。PostgreSQL 和 SQLite 支持在 onConflict 中使用 knex.raw(...),这在指定部分索引条件时很有用。 :::

knex('tableName')
  .insert({
    email: 'ignore@example.com',
    name: 'John Doe',
    active: true,
  })
  // 仅在 email 冲突且 active 为 true 时忽略。
  .onConflict(knex.raw('(email) where active'))
  .ignore();

ignore():发生冲突时静默丢弃插入而不报错。MySQL 使用 INSERT IGNORE,PostgreSQL 和 SQLite 在 insert 语句上追加 ON CONFLICT (columns) DO NOTHING。

knex('tableName')
  .insert({
    email: 'ignore@example.com',
    name: 'John Doe',
  })
  .onConflict('email')
  .ignore();

merge():把 insert 变成 upsert 操作。MySQL 使用 ON DUPLICATE KEY UPDATE,PostgreSQL 和 SQLite 追加 ON CONFLICT (columns) DO UPDATE。默认合并所有列。也支持批量插入:

knex('tableName')
  .insert({
    email: 'ignore@example.com',
    name: 'John Doe',
  })
  .onConflict('email')
  .merge();

// 批量 upsert
knex('tableName')
  .insert([
    { email: 'john@example.com', name: 'John Doe' },
    { email: 'jane@example.com', name: 'Jane Doe' },
    { email: 'alex@example.com', name: 'Alex Doe' },
  ])
  .onConflict('email')
  .merge();

merge(updates):可以只合并一部分列。例如希望插入时设置 created_at、但行已存在时不去更新它:

const timestamp = Date.now();
knex('tableName')
  .insert({
    email: 'ignore@example.com',
    name: 'John Doe',
    created_at: timestamp,
    updated_at: timestamp,
  })
  .onConflict('email')
  .merge(['email', 'name', 'updated_at']);

也可以让"要更新的数据"与"要插入的数据"分离:

const timestamp = Date.now();
knex('tableName')
  .insert({
    email: 'ignore@example.com',
    name: 'John Doe',
    created_at: timestamp,
    updated_at: timestamp,
  })
  .onConflict('email')
  .merge({
    name: 'John Doe The Second',
  });

仅 PostgreSQL/SQLite:还可以在 merge 后追加 where 子句 来条件性更新匹配行:

const timestamp = Date.now();
knex('tableName')
  .insert({
    email: 'ignore@example.com',
    name: 'John Doe',
    created_at: timestamp,
    updated_at: timestamp,
  })
  .onConflict('email')
  .merge({
    name: 'John Doe',
    updated_at: timestamp,
  })
  .where('tableName.updated_at', '<', timestamp);

3.12 upsert(CockroachDB / MySQL)

.upsert(data, [returning], [options]):创建 upsert 查询,接受属性哈希或数组。若传入 returning 数组(如 ['id', 'title']),以包含指定列的"所有新增行"数组兑现,是 returning 的快捷方式。注意 MySQL 不支持 returning 选项。

// 在 title 列有唯一索引的情况下插入新行
knex('books').upsert({ title: 'Great Gatsby' });

// 更新 title 为 'Great Gatsby' 的行,并插入 title 为 'Fahrenheit 451' 的行
knex('books').upsert([{ title: 'Great Gatsby' }, { title: 'Fahrenheit 451' }], ['id']);

// 多行 upsert 时空键被规范化,结果 SQL:
// ("x", "y") values (20, default), (default, 30), (10, 20)
knex('coords').upsert([{ x: 20 }, { y: 30 }, { x: 10, y: 20 }]);

3.13 update / updateFrom

.update(data, [returning], [options]) 或 .update(key, value, [returning], [options]):创建 update 查询,接受属性哈希或键值对,并基于其他查询约束更新。若传入 returning 数组(如 ['id', 'title']),以包含指定列的"所有更新行"数组兑现,是 returning 的快捷方式。

knex('books').where('published_date', '<', 2000).update({
  status: 'archived',
  thisKeyIsSkipped: undefined,
});

// "mysql"、"sqlite"、"oracle" 返回 [1];"postgresql" 返回 []
// 除非设置了 'returning' 参数。
knex('books').update('title', 'Slaughterhouse Five');

/** 返回
 * [{
 *   id: 42,
 *   title: "The Hitchhiker's Guide to the Galaxy"
 * }] **/
knex('books').where({ id: 42 }).update(
  {
    title: "The Hitchhiker's Guide to the Galaxy",
  },
  ['id', 'title']
);

同样支持 MSSQL 的 includeTriggerModifications 选项:

knex('books').update({ title: 'Alice in Wonderland' }, ['id', 'title'], {
  includeTriggerModifications: true,
});

.updateFrom(tableName):用于在 PostgreSQL 中定义带显式 'from' 语法的 update 语句,'from' 的表可以在 where 条件中被引用。

knex('accounts')
  .update({ enabled: false })
  .updateFrom('clients')
  .where('accounts.id', '=', 'clients.id')
  .where('clients.active', '=', false);

3.14 del / delete / using

.del([returning], [options]):因为 delete 是 JavaScript 保留字,所以以 del 作为别名。根据查询中的其他条件删除一行或多行,promise/回调以受影响行数兑现。

knex('accounts').where('activated', false).del();

MSSQL 触发器场景同样可用 includeTriggerModifications:

knex('books')
  .where('title', 'Alice in Wonderland')
  .del(['id', 'title'], { includeTriggerModifications: true });

PostgreSQL 的 delete 支持经典 'join' 语法与 'using' 语法两种方式:

// join 语法
knex('accounts')
  .where('activated', false)
  .join('accounts', 'accounts.id', 'users.account_id')
  .del();

// using 语法
knex('accounts')
  .where('activated', false)
  .using('accounts')
  .whereRaw('accounts.id = users.account_id')
  .del();

.using(tableName|tableNames):用于在 PostgreSQL 中定义带显式 'using' 语法的 delete 语句。

3.15 returning

.returning(column, [options]) / .returning([column1, column2, ...], [options]):PostgreSQL、MSSQL、SQLite 和 Oracle 使用。指定 insert、update、delete 方法应返回哪些列。column 可以是字符串或字符串数组。SQL 结果以对象数组报告,每个对象为每个指定列各含一个属性。Amazon Redshift 不支持 returning。

// 返回 [ { id: 1 } ]
knex('books').returning('id').insert({ title: 'Slaughterhouse Five' });

// "mysql"、"sqlite" 返回 [{ id: 2 }];"postgresql" 返回 [ { id: 2 }, { id: 3 } ]
knex('books')
  .returning('id')
  .insert([{ title: 'Great Gatsby' }, { title: 'Fahrenheit 451' }]);

// 返回 [ { id: 1, title: 'Slaughterhouse Five' } ]
knex('books')
  .returning(['id', 'title'])
  .insert({ title: 'Slaughterhouse Five' });

MSSQL 触发器场景:returning(['id', 'title'], { includeTriggerModifications: true })。

3.16 事务相关:transacting 与行锁

.transacting(transactionObj):由 knex.transaction 使用,可链到任意查询上并传入希望让该查询加入其事务的对象。

const Promise = require('bluebird');
knex
  .transaction(function (trx) {
    knex('books')
      .transacting(trx)
      .insert({ name: 'Old Books' })
      .then(function (resp) {
        const id = resp[0];
        return someExternalMethod(id, trx);
      })
      .then(trx.commit)
      .catch(trx.rollback);
  })
  .then(function (resp) {
    console.log('Transaction complete.');
  })
  .catch(function (err) {
    console.error(err);
  });

以下锁方法在指定事务后动态添加:

  • .transacting(t).forUpdate():select 时在 PostgreSQL/MySQL 添加 FOR UPDATE。Amazon Redshift 因缺乏表锁不支持。
  • .transacting(t).forShare():PostgreSQL 添加 FOR SHARE,MySQL 添加 LOCK IN SHARE MODE。Redshift 不支持。
  • .transacting(t).forNoKeyUpdate():PostgreSQL 添加 FOR NO KEY UPDATE。
  • .transacting(t).forKeyShare():PostgreSQL 添加 FOR KEY SHARE。
  • .skipLocked():MySQL 8.0+、MariaDB-10.6+ 和 PostgreSQL 9.5+。在 forUpdate/forShare 之后使用,跳过任何被锁定的行;若没有可用行则返回空集。
  • .noWait():MySQL 8.0+、MariaDB-10.3+ 和 PostgreSQL 9.5+。在 forUpdate/forShare 之后使用,若任何选中的行当前被锁定,则查询立即失败。
knex('tableName').transacting(trx).forUpdate().select('*');
knex('tableName').transacting(trx).forShare().select('*');
knex('tableName').transacting(trx).forNoKeyUpdate().select('*');
knex('tableName').transacting(trx).forKeyShare().select('*');
knex('tableName').select('*').forUpdate().skipLocked();
knex('tableName').select('*').forUpdate().noWait();

3.17 聚合:count / min / max / sum / avg

.count(column|columns|raw, [options]):对指定列或列数组计数(部分驱动不支持多列),也接受 raw 表达式。count 及其他聚合查询返回对象数组,如 [{'COUNT(*)': 1}];实际键名随方言而异,因此通常建议指定别名(见下面示例)。注意 PostgreSQL 中 count 返回 bigint,在 JS 里是 String 而非 Number。

knex('users').count('active');
knex('users').count('active', { as: 'a' });
knex('users').count('active as a');
knex('users').count({ a: 'active' });
knex('users').count({ a: 'active', v: 'valid' });
knex('users').count('id', 'active');
knex('users').count({ count: ['id', 'active'] });
knex('users').count(knex.raw('??', ['active']));

count 的 TypeScript 类型:默认是 string | number。因为部分连接器(如 postgres)会在 JS 的 Number 不足以容纳时把 BigInt 结果转成 string,这可能会违反直觉。

knex('users').count('age'); // Resolves to: Record<string, number | string>
knex('users').count({ count: '*' }); // Resolves to { count?: string | number | undefined; }

不想处理 string | number 时有两种替代方案:

// 显式声明想要的结果类型:
knex('users').count<Record<string, number>>('age');

// 一次性声明:让 knex 对所有 count/countDistinct 调用使用 number 作为结果类型
declare module 'knex/types/result' {
  interface Registry {
    Count: number;
  }
}

聚合内去重可用 countDistinct:

knex('users').countDistinct('active');

.min(column|columns|raw, [options]):获取指定列的最小值,同样接受 raw 表达式与别名对象/数组语法:

knex('users').min('age');
knex('users').min('age', { as: 'a' });
knex('users').min('age as a');
knex('users').min({ a: 'age' });
knex('users').min({ a: 'age', b: 'experience' });
knex('users').min('age', 'logins');
knex('users').min({ min: ['age', 'logins'] });
knex('users').min(knex.raw('??', ['age']));

.max(column|columns|raw, [options]):获取最大值,语法与 min 一致:

knex('users').max('age');
knex('users').max('age', { as: 'a' });
knex('users').max('age as a');
knex('users').max({ a: 'age' });
knex('users').max('age', 'logins');
knex('users').max({ max: ['age', 'logins'] });
knex('users').max({ max: 'age', exp: 'experience' });
knex('users').max(knex.raw('??', ['age']));

.sum(column|columns|raw):求指定列之和,支持别名对象/数组与 raw。sumDistinct 在聚合函数内添加 distinct:

knex('users').sum('products');
knex('users').sum('products as p');
knex('users').sum({ p: 'products' });
knex('users').sum('products', 'orders');
knex('users').sum({ sum: ['products', 'orders'] });
knex('users').sum(knex.raw('??', ['products']));
knex('users').sumDistinct('products');

.avg(column|columns|raw):求平均值,语法同上;avgDistinct 在聚合内添加 distinct:

knex('users').avg('age');
knex('users').avg('age as a');
knex('users').avg({ a: 'age' });
knex('users').avg('age', 'logins');
knex('users').avg({ avg: ['age', 'logins'] });
knex('users').avg(knex.raw('??', ['age']));
knex('users').avgDistinct('age');

3.18 increment / decrement / truncate / pluck / first

.increment(column, amount):按指定量增加列值,column 支持对象语法。源码中默认步长为 1(increment(column, amount = 1),见 lib/query/querybuilder.js)。

knex('accounts').where('userid', '=', 1).increment('balance', 10);
knex('accounts').where('id', '=', 1).increment({
  balance: 10,
  times: 1,
});

.decrement(column, amount):按指定量减少列值,支持对象语法。

knex('accounts').where('userid', '=', 1).decrement('balance', 5);
knex('accounts').where('id', '=', 1).decrement({
  balance: 50,
});

.truncate():清空当前表。

knex('accounts').truncate();

.pluck(id):从结果中抽取指定列,返回由所选值组成的数组。

knex
  .table('users')
  .pluck('id')
  .then(function (ids) {
    console.log(ids);
  });

.first([columns]):类似 select,但只检索并兑现第一条记录。没有匹配行时返回 undefined。

knex
  .table('users')
  .first('id', 'name')
  .then(function (row) {
    console.log(row);
  });

3.19 hintComment / comment / clone

.hintComment(hint|hints):用 /*+ ... */ 的注释式语法为查询添加提示。MySQL 和 Oracle 使用这种语法传优化器提示;各种 DB 代理和路由器也用它传递提示以改变行为。在其他方言中提示只是被当作普通注释忽略。

knex('accounts').where('userid', '=', 1).hintComment('NO_ICP(accounts)');

.comment(comment):用 /* ... */ 语法给 SQL 查询前追加注释。部分字符被禁止,如 /*、*/ 和 ?。

knex('users').where('id', '=', 1).comment('Get user by id');

.clone():克隆当前查询链,便于在别的查询中复用部分查询片段而不改动原查询。从源码看,clone() 会新建同构造器实例并浅拷贝 _method、_single、_comments、_statements、_debug,以及 _options、_queryContext、_connection(见 lib/query/querybuilder.js)。

3.20 窗口函数:denseRank / rank / rowNumber / partitionBy

窗口函数均支持四种语法,alias 可设为 falsy 值表示不需要别名:

String Syntax — .denseRank(alias, orderByClause, [partitionByClause]):

knex('users').select('*').denseRank('alias_name', 'email', 'firstName');

数组参数:

knex('users')
  .select('*')
  .denseRank('alias_name', ['email', 'address'], ['firstName', 'lastName']);

Raw Syntax — .denseRank(alias, rawQuery):

knex('users')
  .select('*')
  .denseRank('alias_name', knex.raw('order by ??', ['email']));

Function Syntax — .denseRank(alias, function):在函数内使用可链式的 orderBy() 与 partitionBy() 构建:

knex('users')
  .select('*')
  .denseRank('alias_name', function () {
    this.orderBy('email').partitionBy('firstName');
  });

.rank(alias, ~mixed~) 添加 rank() 调用,四种语法与 denseRank 完全一致:

knex('users').select('*').rank('alias_name', 'email', 'firstName');
knex('users')
  .select('*')
  .rank('alias_name', ['email', 'address'], ['firstName', 'lastName']);
knex('users').select('*').rank('alias_name', knex.raw('order by ??', ['email']));
knex('users')
  .select('*')
  .rank('alias_name', function () {
    this.orderBy('email').partitionBy('firstName');
  });

.rowNumber(alias, ~mixed~) 添加 row_number() 调用,四种语法同上:

knex('users').select('*').rowNumber('alias_name', 'email', 'firstName');
knex('users')
  .select('*')
  .rowNumber('alias_name', ['email', 'address'], ['firstName', 'lastName']);
knex('users').select('*').rowNumber('alias_name', knex.raw('order by ??', ['email']));
knex('users')
  .select('*')
  .rowNumber('alias_name', function () {
    this.orderBy('email').partitionBy('firstName');
  });

.partitionBy(column, direction):按指定列对 rowNumber、denseRank、rank 分区。不提供 direction 时默认升序。

// 无方向排序
knex('users')
  .select('*')
  .rowNumber('alias_name', function () {
    this.partitionBy('firstName');
  });

// 带方向排序
knex('users')
  .select('*')
  .rowNumber('alias_name', function () {
    this.partitionBy('firstName', 'desc');
  });

// 多对象
knex('users')
  .select('*')
  .rowNumber('alias_name', function () {
    this.partitionBy([
      { column: 'firstName', order: 'asc' },
      { column: 'lastName', order: 'desc' },
    ]);
  });

3.21 modify:查询片段复用

.modify(fn, *arguments):允许把查询片段和公共行为封装成函数复用。回调函数的第一个参数是查询构建器,其后跟着传给 modify 的其余(可选)参数。

const withUserName = function (queryBuilder, foreignKey) {
  queryBuilder
    .leftJoin('users', foreignKey, 'users.id')
    .select('users.user_name');
};

knex
  .table('articles')
  .select('title', 'body')
  .modify(withUserName, 'articles_user.id')
  .then(function (article) {
    console.log(article.user_name);
  });

3.22 columnInfo / debug / connection / options / queryContext

.columnInfo([columnName]):返回当前表的列信息对象;传入单个列名则只返回该列信息,包含以下键:defaultValue(默认值)、type(列类型)、maxLength(最大长度)、nullable(是否可为 null)。

knex('users')
  .columnInfo()
  .then(function (info) {
    /*...*/
  });

.debug([enabled]):覆盖当前查询链的全局 debug 设置。省略 enabled 时打开查询调试。

.connection(dbConnection):不使用连接池,为查询设置使用的数据库连接。应传入与对应驱动 acquireConnection() 返回的相同对象:

const Pool = require('pg-pool');
const pool = new Pool({
  /* ... */
});
const connection = await pool.connect();

try {
  return await knex.connection(connection); // knex 是已构建好查询的查询构建器
} catch (error) {
  // 处理错误
} finally {
  connection.release();
}

.options():混入数据库客户端特定库定义的额外选项:

knex('accounts as a1')
  .leftJoin('accounts as a2', function () {
    this.on('a1.email', '<>', 'a2.email');
  })
  .select(['a1.email', 'a2.email'])
  .where(knex.raw('a1.id = 1'))
  .options({ nestTables: true, rowMode: 'array' })
  .limit(2)
  .then({
    /*...*/
  });

::: info Better-SQLite3 better-sqlite3 可以把整数返回为普通 JS number(默认)或 bigint。可以在每个查询上用 .options({safeIntegers: boolean}) 配置:

// {balance: bigint}[]
const rows = await knex('accounts')
  .select('balance')
  .options({ safeIntegers: true });

// {balance: number}[]
const rows = await knex('accounts')
  .select('balance')
  .options({ safeIntegers: false });

所有查询的默认值可通过全局配置选项设置(参见 docs/src/guide/index.md)。 :::

.queryContext(context):配置传给 wrapIdentifier 与 postProcessResponse 钩子的上下文(参见 docs/src/guide/index.md):

knex('accounts as a1')
  .queryContext({ foo: 'bar' })
  .select(['a1.email', 'a2.email']);

上下文可以是任意值,会被原样传给钩子。但要注意:当查询构建器被 clone 时,对象会被浅克隆——克隆体包含原对象的所有属性,但引用不同,因此可以安全地修改克隆实例的上下文。不带参数调用 queryContext() 会返回该查询构建器已配置的上下文。

四、扩展 Query Builder(实验特性)

注意:该特性是实验性的,API 未来可能变化。 它允许给 Query Builder 添加自定义函数:

const { knex } = require('knex');
knex.QueryBuilder.extend('customSelect', function (value) {
  return this.select(this.client.raw(`${value} as value`));
});

const meaningOfLife = await knex('accounts').customSelect(42);

源码层面,Builder.extend = (methodName, fn) 会把函数挂到 Builder 原型上,且会拒绝覆盖已存在的方法(抛出 Can't extend QueryBuilder with existing method ('${methodName}'),见 lib/query/querybuilder.js)。

TypeScript 用户可按以下步骤扩展接口:

  1. 在 @types 文件夹(或其他任意文件夹)中创建 knex.d.ts:
// knex.d.ts

import { Knex as KnexOriginal } from 'knex';

declare module 'knex' {
  namespace Knex {
    interface QueryInterface {
      customSelect<TRecord, TResult>(
        value: number
      ): KnexOriginal.QueryBuilder<TRecord, TResult>;
    }
  }
}
  1. 在 tsconfig.json 的 typeRoots 中加入新的 @types 文件夹:
// tsconfig.json
{
  "compilerOptions": {
    "typeRoots": ["node_modules/@types", "@types"]
  }
}

五、Where 子句全家桶

Knex 提供了多种方法辅助构建动态 where 子句。许多位置可以用函数代替值来构造子查询,大多数位置可以直接使用已有的 knex 查询来组合子查询。

重要安全行为:Knex 在查询不健全时会在 SQL 编译阶段抛错。"Where" 子句可能在以下情况抛错:任何 "undefined" 值被传入 where 子句;"where" 子句出现在 "truncate" 语句上。以下查询都会抛错:

knex('accounts').where('login', undefined).select().toSQL();
knex('logs').where('server', 'dev').truncate().toSQL();

5.1 where / orWhere

.where(~mixed~) / .orWhere,支持四种写法:

对象语法:

knex('users')
  .where({
    first_name: 'Test',
    last_name: 'User',
  })
  .select('id');

键值对:

knex('users').where('id', 1);

函数:

knex('users')
  .where((builder) =>
    builder.whereIn('id', [1, 11, 15]).whereNotIn('id', [17, 19])
  )
  .andWhere(function () {
    this.where('id', '>', 10);
  });

分组链式:

knex('users')
  .where(function () {
    this.where('id', 1).orWhere('id', '>', 10);
  })
  .orWhere({ name: 'Tester' });

操作符语法:

knex('users').where('columnName', 'like', '%rowlikeme%');
knex('users').where('votes', '>', 100);

const subquery = knex('users')
  .where('votes', '>', 100)
  .andWhere('status', 'active')
  .orWhere('name', 'John')
  .select('id');

// 以子查询作为 in 的值
knex('accounts').where('id', 'in', subquery);

.orWhere 配合对象会自动包裹语句,生成 or (and - and - and) 子句:

knex('users').where('id', 1).orWhere({ votes: 100, user: 'knex' });

5.2 whereNot / orWhereNot

.whereNot(~mixed~) / .orWhereNot,同样支持对象、键值对、分组链式、操作符四种语法:

knex('users')
  .whereNot({
    first_name: 'Test',
    last_name: 'User',
  })
  .select('id');

knex('users').whereNot('id', 1);

knex('users')
  .whereNot(function () {
    this.where('id', 1).orWhereNot('id', '>', 10);
  })
  .orWhereNot({ name: 'Tester' });

knex('users').whereNot('votes', '>', 100);

::: warning WhereNot 不适合 "in" 和 "between" 类型的子查询,应改用 "not in" 和 "not between"。 :::

const subquery = knex('users')
  .whereNot('votes', '>', 100)
  .andWhere('status', 'active')
  .orWhere('name', 'John')
  .select('id');

knex('accounts').where('id', 'not in', subquery);

5.3 whereIn / whereNotIn

.whereIn(column|columns, array|callback|builder) / .orWhereIn:是 .where('id', 'in', obj) 的简写。注意传入空数组作为值时,查询永远不会返回任何行(WHERE 1 = 0)。

knex
  .select('name')
  .from('users')
  .whereIn('id', [1, 2, 3])
  .orWhereIn('id', [4, 5, 6]);

// 回调子查询
knex
  .select('name')
  .from('users')
  .whereIn('account_id', function () {
    this.select('id').from('accounts');
  });

// builder 子查询
const subquery = knex.select('id').from('accounts');
knex.select('name').from('users').whereIn('account_id', subquery);

// 复合列 in
knex
  .select('name')
  .from('users')
  .whereIn(
    ['account_id', 'email'],
    [
      [3, 'test3@example.com'],
      [4, 'test4@example.com'],
    ]
  );

// 复合列 in + builder
knex
  .select('name')
  .from('users')
  .whereIn(
    ['account_id', 'email'],
    knex.select('id', 'email').from('accounts')
  );

.whereNotIn(column, array|callback|builder) / .orWhereNotIn:

knex('users').whereNotIn('id', [1, 2, 3]);
knex('users').where('name', 'like', '%Test%').orWhereNotIn('id', [1, 2, 3]);

5.4 whereNull / whereNotNull

knex('users').whereNull('updated_at');
knex('users').whereNotNull('created_at');

分别有对应的 .orWhereNull 与 .orWhereNotNull。

5.5 whereExists / whereNotExists

.whereExists(builder | callback) / .orWhereExists:

knex('users').whereExists(function () {
  this.select('*').from('accounts').whereRaw('users.account_id = accounts.id');
});

knex('users').whereExists(
  knex.select('*').from('accounts').whereRaw('users.account_id = accounts.id')
);

.whereNotExists(builder | callback) / .orWhereNotExists:

knex('users').whereNotExists(function () {
  this.select('*').from('accounts').whereRaw('users.account_id = accounts.id');
});

knex('users').whereNotExists(
  knex.select('*').from('accounts').whereRaw('users.account_id = accounts.id')
);

5.6 whereBetween / whereNotBetween

knex('users').whereBetween('votes', [1, 100]);
knex('users').whereNotBetween('votes', [1, 100]);

分别有对应的 .orWhereBetween 与 .orWhereNotBetween。

5.7 whereRaw

.whereRaw(query, [bindings]):是 .where(knex.raw(query)) 的便捷助手。

knex('users').whereRaw('id = ?', [1]);

5.8 whereLike / whereILike

.whereLike(column, string|builder|raw) / .orWhereLike:对指定列做区分大小写的子串比较。

knex('users').whereLike('email', '%mail%');

knex('users')
  .whereLike('email', '%mail%')
  .andWhereLike('email', '%.com')
  .orWhereLike('email', '%name%');

.whereILike(column, string|builder|raw) / .orWhereILike:不区分大小写的子串比较。

knex('users').whereILike('email', '%mail%');

knex('users')
  .whereILike('email', '%MAIL%')
  .andWhereILike('email', '%.COM')
  .orWhereILike('email', '%NAME%');

5.9 JSON 相关 where

.whereJsonObject(column, string|json|builder|raw):对指定 json 列做 json 对象比较。

knex('users').whereJsonObject('json_col', { name: 'user_name' });

.whereJsonPath(column, jsonPath, operator, value):把 JsonPath 返回的值与某个值做比较。

knex('users').whereJsonPath('json_col', '$.age', '>', 18);
knex('users').whereJsonPath('json_col', '$.name', '=', 'username');

.whereJsonSupersetOf(column, string|json|builder|raw):当 json 列包含给定值时比较为真。仅 MySQL、PostgreSQL 和 CockroachDB。

knex('users').whereJsonSupersetOf('hobbies', { sport: 'foot' });

.whereJsonSubsetOf(column, string|json|builder|raw):当 json 列被包含在给定值中时比较为真。仅 MySQL、PostgreSQL 和 CockroachDB。

// 给定 hobby 列为 { "sport" : "tennis" } 时,该 where 为真
knex('users').whereJsonSubsetOf('hobby', { sport: 'tennis', book: 'fantasy' });

六、Join 方法

6.1 join

.join(table, first, [operator], second):第一个参数是连接表,后三个参数依次是第一个连接列、连接操作符、第二个连接列。操作符可以省略:

knex('users')
  .join('contacts', 'users.id', '=', 'contacts.user_id')
  .select('users.id', 'contacts.phone');

knex('users')
  .join('contacts', 'users.id', 'contacts.user_id')
  .select('users.id', 'contacts.phone');

分组 join:把函数作为第二个参数,在函数内用 on 配合 orOn/andOn 构建带括号分组的 join:

knex
  .select('*')
  .from('users')
  .join('accounts', function () {
    this.on('accounts.id', '=', 'users.account_id').orOn(
      'accounts.owner_id',
      '=',
      'users.id'
    );
  });

嵌套 join:把函数作为 on、orOn 或 andOn 的第一个参数:

knex
  .select('*')
  .from('users')
  .join('accounts', function () {
    this.on(function () {
      this.on('accounts.id', '=', 'users.account_id');
      this.orOn('accounts.owner_id', '=', 'users.id');
    });
  });

对象语法:

knex
  .select('*')
  .from('users')
  .join('accounts', { 'accounts.id': 'users.account_id' });

字面值 join:需要在 join 中使用字面值(字符串、数字或布尔)而不是列时,使用 knex.raw:

knex
  .select('*')
  .from('users')
  .join('accounts', 'accounts.type', knex.raw('?', ['admin']));

6.2 innerJoin / leftJoin / leftOuterJoin / rightJoin / rightOuterJoin / fullOuterJoin / crossJoin

.innerJoin(table, ~mixed~):

knex.from('users').innerJoin('accounts', 'users.id', 'accounts.user_id');
knex.table('users').innerJoin('accounts', 'users.id', '=', 'accounts.user_id');
knex('users').innerJoin('accounts', function () {
  this.on('accounts.id', '=', 'users.account_id').orOn(
    'accounts.owner_id',
    '=',
    'users.id'
  );
});

.leftJoin(table, ~mixed~):

knex
  .select('*')
  .from('users')
  .leftJoin('accounts', 'users.id', 'accounts.user_id');

knex
  .select('*')
  .from('users')
  .leftJoin('accounts', function () {
    this.on('accounts.id', '=', 'users.account_id').orOn(
      'accounts.owner_id',
      '=',
      'users.id'
    );
  });

.leftOuterJoin(table, ~mixed~):用法与 leftJoin 相同:

knex
  .select('*')
  .from('users')
  .leftOuterJoin('accounts', 'users.id', 'accounts.user_id');

knex
  .select('*')
  .from('users')
  .leftOuterJoin('accounts', function () {
    this.on('accounts.id', '=', 'users.account_id').orOn(
      'accounts.owner_id',
      '=',
      'users.id'
    );
  });

.rightJoin(table, ~mixed~):

knex
  .select('*')
  .from('users')
  .rightJoin('accounts', 'users.id', 'accounts.user_id');

knex
  .select('*')
  .from('users')
  .rightJoin('accounts', function () {
    this.on('accounts.id', '=', 'users.account_id').orOn(
      'accounts.owner_id',
      '=',
      'users.id'
    );
  });

.rightOuterJoin(table, ~mixed~):

knex
  .select('*')
  .from('users')
  .rightOuterJoin('accounts', 'users.id', 'accounts.user_id');

knex
  .select('*')
  .from('users')
  .rightOuterJoin('accounts', function () {
    this.on('accounts.id', '=', 'users.account_id').orOn(
      'accounts.owner_id',
      '=',
      'users.id'
    );
  });

.fullOuterJoin(table, ~mixed~):

knex
  .select('*')
  .from('users')
  .fullOuterJoin('accounts', 'users.id', 'accounts.user_id');

knex
  .select('*')
  .from('users')
  .fullOuterJoin('accounts', function () {
    this.on('accounts.id', '=', 'users.account_id').orOn(
      'accounts.owner_id',
      '=',
      'users.id'
    );
  });

.crossJoin(table, ~mixed~):cross join 条件仅 MySQL 和 SQLite3 支持,需要连接条件时请改用 innerJoin。

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

knex
  .select('*')
  .from('users')
  .crossJoin('accounts', 'users.id', 'accounts.user_id');

knex
  .select('*')
  .from('users')
  .crossJoin('accounts', function () {
    this.on('accounts.id', '=', 'users.account_id').orOn(
      'accounts.owner_id',
      '=',
      'users.id'
    );
  });

6.3 joinRaw

.joinRaw(sql, [bindings]):

knex
  .select('*')
  .from('accounts')
  .joinRaw('natural full join table1')
  .where('id', 1);

knex
  .select('*')
  .from('accounts')
  .join(knex.raw('natural full join table1'))
  .where('id', 1);

七、OnClauses:join 内部的条件方法

以下方法都应在 join 的函数体内使用:

.onIn(column, values):

knex
  .select('*')
  .from('users')
  .join('contacts', function () {
    this.on('users.id', '=', 'contacts.id').onIn('contacts.id', [7, 15, 23, 41]);
  });

.onNotIn(column, values):

knex
  .select('*')
  .from('users')
  .join('contacts', function () {
    this.on('users.id', '=', 'contacts.id').onNotIn(
      'contacts.id',
      [7, 15, 23, 41]
    );
  });

.onNull(column):

knex
  .select('*')
  .from('users')
  .join('contacts', function () {
    this.on('users.id', '=', 'contacts.id').onNull('contacts.email');
  });

.onNotNull(column):

knex
  .select('*')
  .from('users')
  .join('contacts', function () {
    this.on('users.id', '=', 'contacts.id').onNotNull('contacts.email');
  });

.onExists(builder | callback):

knex
  .select('*')
  .from('users')
  .join('contacts', function () {
    this.on('users.id', '=', 'contacts.id').onExists(function () {
      this.select('*').from('accounts').whereRaw('users.account_id = accounts.id');
    });
  });

.onNotExists(builder | callback):

knex
  .select('*')
  .from('users')
  .join('contacts', function () {
    this.on('users.id', '=', 'contacts.id').onNotExists(function () {
      this.select('*').from('accounts').whereRaw('users.account_id = accounts.id');
    });
  });

.onBetween(column, range):

knex
  .select('*')
  .from('users')
  .join('contacts', function () {
    this.on('users.id', '=', 'contacts.id').onBetween('contacts.id', [5, 30]);
  });

.onNotBetween(column, range):

knex
  .select('*')
  .from('users')
  .join('contacts', function () {
    this.on('users.id', '=', 'contacts.id').onNotBetween('contacts.id', [5, 30]);
  });

.onJsonPathEquals(column, range):在两个 json 列的 JsonPath 返回值相等时执行 join。

knex('cities')
  .select('cities.name as cityName', 'country.name as countryName')
  .join('country', function () {
    this.onJsonPathEquals(
      // cities 中的 json 列
      'country_name',
      // 'country_name' 列中指向国家名的 json path
      '$.country.name',
      // country 中的 json 列
      'description',
      // 'description' 列中的 json 字段
      '$.name'
    );
  });

八、ClearClauses:清理子句

8.1 clear

.clear(statement):从查询中清除指定操作符。可用操作符:'select'(别名 'columns')、'with'、'select'、'columns'、'where'、'union'、'join'、'group'、'order'、'having'、'limit'、'offset'、'counter'、'counters'。其中 counter(s) 是 .clearCounter() 方法的别名。

knex
  .select('email', 'name')
  .from('users')
  .where('id', '<', 10)
  .clear('select')
  .clear('where');

8.2 各专项 clear 方法

以下方法均已标记为 deprecated,请改用 clear(...),但功能仍可用(均排除子查询):

  • .clearSelect():清除所有 select 子句。knex.select('email', 'name').from('users').clearSelect();
  • .clearWhere():清除所有 where 子句。knex.select('email', 'name').from('users').where('id', 1).clearWhere();
  • .clearGroup():清除所有 group 子句。knex.select().from('users').groupBy('id').clearGroup();
  • .clearOrder():清除所有 order 子句。knex.select().from('users').orderBy('name', 'desc').clearOrder();
  • .clearHaving():清除所有 having 子句。knex.select().from('users').having('id', '>', 5).clearHaving();
  • .clearCounters():清除查询中的所有 increment/decrement 子句。
knex('accounts')
  .where('id', '=', 1)
  .update({ email: 'foo@bar.com' })
  .decrement({
    balance: 50,
  })
  .clearCounters();

8.3 distinct / distinctOn

.distinct([*columns]):为查询设置 distinct 子句。参数为 falsy 或空数组时回退到 *。

// select distinct 'first_name' from customers
knex('customers').distinct('first_name', 'last_name');

// 消除重复行的 select
knex('customers').distinct();

.distinctOn([*columns]):仅 PostgreSQL。添加 distinctOn 子句。

knex('users').distinctOn('age');

8.4 groupBy / groupByRaw

.groupBy(*names):为查询添加 group by 子句。

knex('users').groupBy('count');

.groupByRaw(sql):添加 raw 形式的 group by 子句。

knex
  .select('year', knex.raw('SUM(profit)'))
  .from('sales')
  .groupByRaw('year WITH ROLLUP');

8.5 orderBy / orderByRaw

.orderBy(column|columns, [direction], [nulls]):为查询添加 order by 子句。column 可以是字符串,或字符串与对象的混合列表。nulls 指定空值放置位置(可为 'first' 或 'last')。

单列:

knex('users').orderBy('email');
knex('users').orderBy('name', 'desc');
knex('users').orderBy('name', 'desc', 'first');

多列:

knex('users').orderBy(['email', { column: 'age', order: 'desc' }]);
knex('users').orderBy([{ column: 'email' }, { column: 'age', order: 'desc' }]);
knex('users').orderBy([
  { column: 'email' },
  { column: 'age', order: 'desc', nulls: 'last' },
]);

.orderByRaw(sql):添加 raw 形式的 order by 子句。

knex.select('*').from('table').orderByRaw('col DESC NULLS LAST');

九、Having 子句

重要安全行为:Knex 在查询不健全时会在 SQL 编译阶段抛错。"Having" 子句可能在 having 子句出现在 "delete" 或 "truncate" 语句上时抛错:

knex('accounts').having('login', '=', 'user').del().toSQL();
knex('logs').having('server', '=', 'dev').truncate().toSQL();

.having(column, operator, value):

knex('users')
  .groupBy('count')
  .orderBy('name', 'desc')
  .having('count', '>', 100);

.havingIn(column, values):

knex.select('*').from('users').havingIn('id', [5, 3, 10, 17]);

.havingNotIn(column, values):

knex.select('*').from('users').havingNotIn('id', [5, 3, 10, 17]);

.havingNull(column):

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

.havingNotNull(column):

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

.havingExists(builder | callback):

knex
  .select('*')
  .from('users')
  .havingExists(function () {
    this.select('*').from('accounts').whereRaw('users.account_id = accounts.id');
  });

.havingNotExists(builder | callback):

knex
  .select('*')
  .from('users')
  .havingNotExists(function () {
    this.select('*').from('accounts').whereRaw('users.account_id = accounts.id');
  });

.havingBetween(column, range):

knex.select('*').from('users').havingBetween('id', [5, 10]);

.havingNotBetween(column, range):

knex.select('*').from('users').havingNotBetween('id', [5, 10]);

.havingRaw(sql, [bindings]):

knex('users')
  .groupBy('count')
  .orderBy('name', 'desc')
  .havingRaw('count > ?', [100]);

十、继续深入

登录后查看全文
knex