结构构建器
¥Schema Builder
knex.schema
是一个 getter 函数,它返回一个包含查询的有状态对象。因此,请确保为每个查询获取 knex.schema
的新实例。这些方法返回 promises。
¥The knex.schema
is a getter function, which returns a stateful object containing the query. Therefore be sure to obtain a new instance of the knex.schema
for every query. These methods return promises.
概要
¥Essentials
withSchema
knex.schema.withSchema([schemaName])
指定使用架构构建命令时要使用的架构。
¥Specifies the schema to be used when using the schema-building commands.
knex.schema.withSchema('public').createTable('users', function (table) {
table.increments();
})
createTable
knex.schema.createTable(tableName, callback)
使用架构构建命令在数据库上创建一个新表,并使用回调函数来修改表的结构。
¥Creates a new table on the database, with a callback function to modify the table's structure, using the schema-building commands.
knex.schema.createTable('users', function (table) {
table.increments();
table.string('name');
table.timestamps();
})
createTableLike
knex.schema.createTableLike(tableName, tableNameToCopy, [callback])
基于另一个表在数据库上创建一个新表。仅复制结构:列、键和索引(在 SQL Server 上预计仅复制列)而不复制数据。可以指定回调函数来在复制表中添加列。
¥Creates a new table on the database based on another table. Copy only the structure : columns, keys and indexes (expected on SQL Server which only copy columns) and not the data. Callback function can be specified to add columns in the duplicated table.
knex.schema.createTableLike('new_users', 'users')
// "new_users" table contains columns
// of users and two new columns 'age' and 'last_name'.
knex.schema.createTableLike('new_users', 'users', (table) => {
table.integer('age');
table.string('last_name');
})
dropTable
knex.schema.dropTable(tableName)
删除由 tableName 指定的表。
¥Drops a table, specified by tableName.
knex.schema.dropTable('users')
dropTableIfExists
knex.schema.dropTableIfExists(tableName)
如果表存在(由 tableName 指定),则有条件地删除该表。
¥Drops a table conditionally if the table exists, specified by tableName.
knex.schema.dropTableIfExists('users')
renameTable
knex.schema.renameTable(from, to)
将表从当前 tableName 重命名为另一个。
¥Renames a table from a current tableName to another.
knex.schema.renameTable('old_users', 'users')
hasTable
knex.schema.hasTable(tableName)
通过 tableName 检查表是否存在,并用布尔值解析以指示表是否存在。
¥Checks for a table's existence by tableName, resolving with a boolean to signal if the table exists.
knex.schema.hasTable('users').then(function(exists) {
if (!exists) {
return knex.schema.createTable('users', function(t) {
t.increments('id').primary();
t.string('first_name', 100);
t.string('last_name', 100);
t.text('bio');
});
}
});
hasColumn
knex.schema.hasColumn(tableName, columnName)
检查当前表中是否存在列,用布尔值解析 promise,如果列存在则为 true,否则为 false。
¥Checks if a column exists in the current table, resolves the promise with a boolean, true if the column exists, false otherwise.
table
knex.schema.table(tableName, callback)
选择一个数据库表,然后使用回调内的架构构建函数修改该表。
¥Chooses a database table, and then modifies the table, using the Schema Building functions inside of the callback.
knex.schema.table('users', function (table) {
table.dropColumn('name');
table.string('first_name');
table.string('last_name');
})
alterTable
knex.schema.alterTable(tableName, callback)
选择一个数据库表,然后使用回调内的架构构建函数修改该表。
¥Chooses a database table, and then modifies the table, using the Schema Building functions inside of the callback.
knex.schema.alterTable('users', function (table) {
table.dropColumn('name');
table.string('first_name');
table.string('last_name');
})
createView
knex.schema.createView(tableName, callback)
使用架构构建命令在数据库上创建一个新视图,并使用回调函数来修改视图的结构。
¥Creates a new view on the database, with a callback function to modify the view's structure, using the schema-building commands.
knex.schema.createView('users_view', function (view) {
view.columns(['first_name']);
view.as(knex('users').select('first_name').where('age','>', '18'));
})
createViewOrReplace
knex.schema.createViewOrReplace(tableName, callback)
使用架构构建命令创建新视图或在数据库上替换它,并使用回调函数来修改视图的结构。你需要至少以相同的顺序指定相同的列(你可以添加额外的列)。在 SQLite 中,此函数生成删除/创建视图查询(视图列可以不同)。
¥Creates a new view or replace it on the database, with a callback function to modify the view's structure, using the schema-building commands. You need to specify at least the same columns in same order (you can add extra columns). In SQLite, this function generate drop/create view queries (view columns can be different).
knex.schema.createViewOrReplace('users_view', function (view) {
view.columns(['first_name']);
view.as(knex('users').select('first_name').where('age','>', '18'));
})
createMaterializedView
knex.schema.createMaterializedView(viewName, callback)
使用架构构建命令在数据库上创建一个新的物化视图,并使用回调函数来修改视图的结构。仅适用于 PostgreSQL、CockroachDb、Redshift 和 Oracle。
¥Creates a new materialized view on the database, with a callback function to modify the view's structure, using the schema-building commands. Only on PostgreSQL, CockroachDb, Redshift and Oracle.
knex.schema.createMaterializedView('users_view', function (view) {
view.columns(['first_name']);
view.as(knex('users').select('first_name').where('age','>', '18'));
})
refreshMaterializedView
knex.schema.refreshMaterializedView(viewName)
刷新数据库的物化视图。仅适用于 PostgreSQL、CockroachDb、Redshift 和 Oracle。
¥Refresh materialized view on the database. Only on PostgreSQL, CockroachDb, Redshift and Oracle.
knex.schema.refreshMaterializedView('users_view')
dropView
knex.schema.dropView(viewName)
删除数据库上的视图。
¥Drop view on the database.
knex.schema.dropView('users_view')
dropViewIfExists
knex.schema.dropViewIfExists(viewName)
删除数据库上的视图(如果存在)。
¥Drop view on the database if exists.
knex.schema.dropViewIfExists('users_view')
dropMaterializedView
knex.schema.dropMaterializedView(viewName)
将物化视图删除到数据库上。仅适用于 PostgreSQL、CockroachDb、Redshift 和 Oracle。
¥Drop materialized view on the database. Only on PostgreSQL, CockroachDb, Redshift and Oracle.
knex.schema.dropMaterializedView('users_view')
dropMaterializedViewIfExists
knex.schema.dropMaterializedViewIfExists(viewName)
删除数据库上的物化视图(如果存在)。仅适用于 PostgreSQL、CockroachDb、Redshift 和 Oracle。
¥Drop materialized view on the database if exists. Only on PostgreSQL, CockroachDb, Redshift and Oracle.
knex.schema.dropMaterializedViewIfExists('users_view')
renameView
knex.schema.renameView(viewName)
重命名数据库中的现有视图。Oracle 和 SQLite 不支持。
¥Rename a existing view in the database. Not supported by Oracle and SQLite.
knex.schema.renameView('users_view')
alterView
knex.schema.alterView(viewName)
更改视图以重命名列或更改默认值。仅适用于 PostgreSQL、MSSQL 和 Redshift。
¥Alter view to rename columns or change default values. Only available on PostgreSQL, MSSQL and Redshift.
knex.schema.alterView('view_test', function (view) {
view.column('first_name').rename('name_user');
view.column('bio').defaultTo('empty');
})
generateDdlCommands
knex.schema.generateDdlCommands()
生成完整的 SQL 命令以应用所描述的架构更改,而不执行任何操作。当 knex 纯粹用作查询构建器时很有用。通常会产生与 .toSQL() 相同的结果,但 SQLite 存在一个明显的例外,它依赖于对数据库的异步调用来构建其部分架构修改语句
¥Generates complete SQL commands for applying described schema changes, without executing anything. Useful when knex is being used purely as a query builder. Generally produces same result as .toSQL(), with a notable exception with SQLite, which relies on asynchronous calls to the database for building part of its schema modification statements
const ddlCommands = knex.schema.alterTable(
'users',
(table) => {
table
.foreign('companyId')
.references('company.companyId')
.withKeyName('fk_fkey_company');
}
).generateDdlCommands();
raw
knex.schema.raw(statement)
在架构构建器链中运行任意 SQL 查询。
¥Run an arbitrary sql query in the schema builder chain.
knex.schema.raw("SET sql_mode='TRADITIONAL'")
.table('users', function (table) {
table.dropColumn('name');
table.string('first_name');
table.string('last_name');
})
queryContext
knex.schema.queryContext(context)
允许配置要传递到 wrapIdentifier 钩子的上下文。上下文可以是任何类型的值,并且将不加修改地传递给 wrapIdentifier
。
¥Allows configuring a context to be passed to the wrapIdentifier hook. The context can be any kind of value and will be passed to wrapIdentifier
without modification.
knex.schema.queryContext({ foo: 'bar' })
.table('users', function (table) {
table.string('first_name');
table.string('last_name');
})
对于需要格式化的每个标识符,配置的上下文将传递到 wrapIdentifier
,包括表名和列名。但是,可以通过 table.queryContext 为列名称设置不同的上下文。
¥The context configured will be passed to wrapIdentifier
for each identifier that needs to be formatted, including the table and column names. However, a different context can be set for the column names via table.queryContext.
不带参数调用 queryContext
将返回为架构构建器实例配置的任何上下文。
¥Calling queryContext
with no arguments will return any context configured for the schema builder instance.
dropSchema
knex.schema.dropSchema(schemaName, [cascade])
删除由模式名称指定的模式,并使用可选的级联选项(默认为 false)。仅 PostgreSQL 支持。
¥Drop a schema, specified by the schema's name, with optional cascade option (default to false). Only supported by PostgreSQL.
//drop schema 'public'
knex.schema.dropSchema('public')
//drop schema 'public' cascade
knex.schema.dropSchema('public', true)
dropSchemaIfExists
knex.schema.dropSchemaIfExists(schemaName, [cascade])
如果模式存在,则有条件地删除模式,由模式名称指定,并使用可选的级联选项(默认为 false)。仅 PostgreSQL 支持。
¥Drop a schema conditionally if the schema exists, specified by the schema's name, with optional cascade option (default to false). Only supported by PostgreSQL.
//drop schema if exists 'public'
knex.schema.dropSchemaIfExists('public')
//drop schema if exists 'public' cascade
knex.schema.dropSchemaIfExists('public', true)
结构构建
¥Schema Building
dropColumn
table.dropColumn(name)
删除由列名称指定的列
¥Drops a column, specified by the column's name
dropColumns
table.dropColumns(columns)
删除多列,采用可变数量的列名称。
¥Drops multiple columns, taking a variable number of column names.
renameColumn
table.renameColumn(from, to)
将列从一个名称重命名为另一个名称。
¥Renames a column from one name to another.
increments
table.increments(name, options={[primaryKey: boolean = true])
添加自动递增列。在 PostgreSQL 中这是一个系列;在 Amazon Redshift 中,整数标识 (1,1)。如果该列不在另一个主键中,则这将用作表的主键。如果你希望添加 bigint 递增数字(在 PostgreSQL bigserial 中),还可以使用 bigIncrements。请注意,如果列不在主键中(具有主函数),则默认创建主键,但你可以通过传递 primaryKey
选项来覆盖此行为。如果将此函数与主函数一起使用,则该列将添加到复合主键中。在 SQLite 中,自增列需要为主键,因此如果使用 primary 函数,主键将转换为唯一索引。MySQL 不支持没有主键的自动增量列,因此会生成多个查询来创建 int 列,将增量列添加到复合主键,然后将该列修改为自动增量列。
¥Adds an auto incrementing column. In PostgreSQL this is a serial; in Amazon Redshift an integer identity(1,1). This will be used as the primary key for the table if the column isn't in another primary key. Also available is a bigIncrements if you wish to add a bigint incrementing number (in PostgreSQL bigserial). Note that a primary key is created by default if the column isn't in primary key (with primary function), but you can override this behaviour by passing the primaryKey
option. If you use this function with primary function, the column is added to the composite primary key. With SQLite, autoincrement column need to be a primary key, so if primary function is used, primary keys are transformed in unique index. MySQL don't support autoincrement column without primary key, so multiple queries are generated to create int column, add increments column to composite primary key then modify the column to autoincrement column.
// create table 'users'
// with a primary key using 'increments()'
knex.schema.createTable('users', function (table) {
table.increments('userId');
table.string('name');
});
// create table 'users'
// with a composite primary key ('userId', 'name').
// increments doesn't generate primary key.
knex.schema.createTable('users', function (table) {
table.primary(['userId', 'name']);
table.increments('userId');
table.string('name');
});
// reference the 'users' primary key in new table 'posts'
knex.schema.createTable('posts', function (table) {
table.integer('author').unsigned().notNullable();
table.string('title', 30);
table.string('content');
table.foreign('author').references('userId').inTable('users');
});
可以传递一个 PrimaryKey 选项,以禁用自动主键创建:
¥A primaryKey option may be passed, to disable to automatic primary key creation:
// create table 'users'
// with a primary key using 'increments()'
// but also increments field 'other_id'
// that does not need primary key
knex.schema.createTable('users', function (table) {
table.increments('id');
table.increments('other_id', { primaryKey: false });
});
integer
table.integer(name, length)
添加整数列。在 PostgreSQL 上你不能调整长度,你需要使用其他选项,例如 bigInteger 等
¥Adds an integer column. On PostgreSQL you cannot adjust the length, you need to use other option such as bigInteger, etc
bigInteger
table.bigInteger(name)
在 MySQL 或 PostgreSQL 中,添加一个 bigint 列,否则添加一个普通整数。请注意,bigint 数据在查询中以字符串形式返回,因为 JavaScript 可能无法在不损失精度的情况下解析它们。
¥In MySQL or PostgreSQL, adds a bigint column, otherwise adds a normal integer. Note that bigint data is returned as a string in queries because JavaScript may be unable to parse them without loss of precision.
tinyint
table.tinyint(name, length)
添加一个 tinyint 列
¥Adds a tinyint column
smallint
table.smallint(name)
添加一个 smallint 列
¥Adds a smallint column
mediumint
table.mediumint(name)
添加一个 mediumint 列
¥Adds a mediumint column
bigint
table.bigint(name)
添加一个 bigint 列
¥Adds a bigint column
text
table.text(name, [textType])
添加文本列,并为 MySql 文本数据类型首选项添加可选的 textType。textType 可以是中文本或长文本,否则默认为文本。
¥Adds a text column, with optional textType for MySql text datatype preference. textType may be mediumtext or longtext, otherwise defaults to text.
string
table.string(name, [length])
添加字符串列,可选长度默认为 255。
¥Adds a string column, with optional length defaulting to 255.
float
table.float(column, [precision], [scale])
添加一个浮点列,具有可选的精度(默认为 8)和小数位数(默认为 2)。
¥Adds a float column, with optional precision (defaults to 8) and scale (defaults to 2).
double
table.double(column, [precision], [scale])
添加一个双列,具有可选的精度(默认为 8)和小数位数(默认为 2)。在 SQLite/MSSQL 中,这是一个没有精度/小数位数的浮点数;在 PostgreSQL 中,这是双精度;在 Oracle 中,这是一个具有匹配精度/小数位数的数字。
¥Adds a double column, with optional precision (defaults to 8) and scale (defaults to 2). In SQLite/MSSQL this is a float with no precision/scale; In PostgreSQL this is a double precision; In Oracle this is a number with matching precision/scale.
decimal
table.decimal(column, [precision], [scale])
添加一个小数列,具有可选的精度(默认为 8)和小数位数(默认为 2)。将 NULL 指定为精度会创建一个小数列,该列可以存储任何精度和小数位数的数字。(仅支持 Oracle、SQLite、Postgres)
¥Adds a decimal column, with optional precision (defaults to 8) and scale (defaults to 2). Specifying NULL as precision creates a decimal column that can store numbers of any precision and scale. (Only supported for Oracle, SQLite, Postgres)
boolean
table.boolean(name)
添加布尔列。
¥Adds a boolean column.
date
table.date(name)
添加日期列。
¥Adds a date column.
datetime
table.datetime(name, options={[useTz: boolean], [precision: number]})
添加日期时间列。默认情况下,PostgreSQL 创建带有时区的列(timestamptz 类型)。可以通过传递 useTz 选项(对于 PostgreSQL 默认为 true)来覆盖此行为。MySQL 和 MSSQL 没有 useTz 选项。
¥Adds a datetime column. By default PostgreSQL creates column with timezone (timestamptz type). This behaviour can be overriden by passing the useTz option (which is by default true for PostgreSQL). MySQL and MSSQL do not have useTz option.
可以传递精度选项:
¥A precision option may be passed:
table.datetime('some_time', { precision: 6 }).defaultTo(knex.fn.now(6))
time
table.time(name, [precision])
添加时间列,MySQL 的精度可选。Amazon Redshift 不支持。
¥Adds a time column, with optional precision for MySQL. Not supported on Amazon Redshift.
在 MySQL 中,可以传递精度选项:
¥In MySQL a precision option may be passed:
table.time('some_time', { precision: 6 })
timestamp
table.timestamp(name, options={[useTz: boolean], [precision: number]})
添加时间戳列。默认情况下,PostgreSQL 创建带有时区的列(timestamptz 类型),而 MSSQL 则不创建列(datetime2)。可以通过传递 useTz 选项来覆盖此行为(默认情况下,对于 MSSQL 为 false,对于 PostgreSQL 为 true)。MySQL 没有 useTz 选项。
¥Adds a timestamp column. By default PostgreSQL creates column with timezone (timestamptz type) and MSSQL does not (datetime2). This behaviour can be overriden by passing the useTz option (which is by default false for MSSQL and true for PostgreSQL). MySQL does not have useTz option.
table.timestamp('created_at').defaultTo(knex.fn.now());
在 PostgreSQL 和 MySQL 中,可以传递精度选项:
¥In PostgreSQL and MySQL a precision option may be passed:
table.timestamp('created_at', { precision: 6 }).defaultTo(knex.fn.now(6));
在 PostgreSQL 和 MSSQL 中,可以传递时区选项:
¥In PostgreSQL and MSSQL a timezone option may be passed:
table.timestamp('created_at', { useTz: true });
timestamps
table.timestamps([useTimestamps], [defaultToNow], [useCamelCase])
在数据库中添加 created_at 和 updated_at 列,并将每个列设置为日期时间类型。当 true 作为第一个参数传递时,将使用时间戳类型。当 true 作为第二个参数传递时,两列默认不为空并使用当前时间戳。请注意,在 MySQL 上 .timestamps() 仅具有秒精度,为了获得更好的精度,请直接使用 .datetime 或 .timestamp 方法进行精确计算。如果 useCamelCase 为 true,则列的名称为 createAt 和 UpdatedAt。
¥Adds created_at and updated_at columns on the database, setting each to datetime types. When true is passed as the first argument a timestamp type is used instead. Both columns default to being not null and using the current timestamp when true is passed as the second argument. Note that on MySQL the .timestamps() only have seconds precision, to get better precision use the .datetime or .timestamp methods directly with precision. If useCamelCase is true, the name of columns are createdAt and updatedAt.
信息
PostgreSQL updated_at
字段不会自动更新。详情请参阅此 issue
¥PostgreSQL updated_at
field will not automatically be updated. Please see this issue for details
dropTimestamps
table.dropTimestamps([useCamelCase])
从表中删除创建的列和更新的列,这些列可以通过时间戳创建。如果 useCamelCase 为 true,则列的名称为 createAt 和 UpdatedAt。
¥Drops the columns created_at and updated_at from the table, which can be created via timestamps. If useCamelCase is true, the name of columns are createdAt and updatedAt.
binary
table.binary(name, [length])
添加一个二进制列,带有 MySQL 的可选长度参数。
¥Adds a binary column, with optional length argument for MySQL.
enum / enu
table.enu(col, values, [options])
添加枚举列(别名为 enu,因为 enum 是 JavaScript 中的保留字)。在 Amazon Redshift 上实现为未检查的 varchar(255)。请注意,第二个参数是值数组。示例:
¥Adds a enum column, (aliased to enu, as enum is a reserved word in JavaScript). Implemented as unchecked varchar(255) on Amazon Redshift. Note that the second argument is an array of values. Example:
table.enu('column', ['value1', 'value2'])
对于 Postgres,可以提供额外的选项参数来指定是否使用 Postgres 的原生 TYPE:
¥For Postgres, an additional options argument can be provided to specify whether or not to use Postgres's native TYPE:
table.enu('column', ['value1', 'value2'], { useNative: true, enumName: 'foo_type' })
它将使用提供的值来生成适当的类型。示例:
¥It will use the values provided to generate the appropriate TYPE. Example:
CREATE TYPE "foo_type" AS ENUM ('value1', 'value2');
要跨列使用现有的原生类型,请在选项中指定 'existingType'(假设该类型已创建):
¥To use an existing native type across columns, specify 'existingType' in the options (this assumes the type has already been created):
信息
由于枚举值不用于原生 && 现有类型,因此传入值的类型并不重要。
¥Since the enum values aren't utilized for a native && existing type, the type being passed in for values is immaterial.
table.enu('column', null, { useNative: true, existingType: true, enumName: 'foo_type' })
如果你想使用与当前表的架构不同的架构中的现有枚举,请在选项中指定 'schemaName':
¥If you want to use existing enums from a schema, different from the schema of your current table, specify 'schemaName' in the options:
table.enu('column', null, { useNative: true, existingType: true, enumName: 'foo_type', schemaName: 'public' })
Knex 不提供任何在创建后更改枚举的方法。要稍后更改枚举,你必须使用 Knex.raw 以及适合你的数据库的命令。
¥Knex does not provide any way to alter enumerations after creation. To change an enumeration later on you must use Knex.raw, and the appropriate command for your database.
json
table.json(name)
添加 json 列,使用 PostgreSQL、MySQL 和 SQLite 中内置的 json 类型,在旧版本或不受支持的数据库中默认为文本列。
¥Adds a json column, using the built-in json type in PostgreSQL, MySQL and SQLite, defaulting to a text column in older versions or in unsupported databases.
对于 PostgreSQL,由于原生数组和 json 类型之间不兼容,当将数组(或可能是数组的值)设置为 json 或 jsonb 列的值时,应该使用 JSON.stringify() 将值转换为 在将其传递给查询构建器之前的字符串,例如
¥For PostgreSQL, due to incompatibility between native array and json types, when setting an array (or a value that could be an array) as the value of a json or jsonb column, you should use JSON.stringify() to convert your value to a string prior to passing it to the query builder, e.g.
knex.table('users')
.where({id: 1})
.update({json_data: JSON.stringify(mightBeAnArray)});
jsonb
table.jsonb(name)
添加 jsonb 列。工作方式与 table.json() 类似,但如果可能的话使用原生 jsonb 类型。
¥Adds a jsonb column. Works similar to table.json(), but uses native jsonb type if possible.
uuid
table.uuid(name, options=({[useBinaryUuid:boolean],[primaryKey:boolean]})
添加 uuid 列 - 这使用 PostgreSQL 中的内置 uuid 类型,并在其他数据库中默认回退到 char(36)。如果 useBinaryUuid 为 true,则使用 binary(16)。请参阅 uuidToBin 函数在插入之前将 uuid 转换为二进制,并参阅 binToUuid 将二进制 uuid 转换为 uuid。如果 primaryKey 为 true,那么对于 PostgreSQL,该字段将被配置为 uuid primary key
,对于 CockroackDB,在类型上设置一个额外的 default gen_random_uuid()
。
¥Adds a uuid column - this uses the built-in uuid type in PostgreSQL, and falling back to a char(36) in other databases by default. If useBinaryUuid is true, binary(16) is used. See uuidToBin function to convert uuid in binary before inserting and binToUuid to convert binary uuid to uuid. If primaryKey is true, then for PostgreSQL the field will be configured as uuid primary key
, for CockroackDB an additional default gen_random_uuid()
is set on the type.
你可以将默认值设置为 uuid 辅助函数。Redshift 不支持。
¥You may set the default value to the uuid helper function. Not supported by Redshift.
knex.schema.createTable(tblName, (table) => {
table.uuid('uuidColumn').defaultTo(knex.fn.uuid());
});
geometry
table.geometry(name)
添加几何列。由 SQLite、MSSQL 和 PostgreSQL 支持。
¥Adds a geometry column. Supported by SQLite, MSSQL and PostgreSQL.
knex.schema.createTable(tblName, (table) => {
table.geometry('geometryColumn');
});
geography
table.geography(name)
添加地理栏目。由 SQLite、MSSQL 和 PostgreSQL(在 PostGIS 扩展中)支持。
¥Adds a geography column. Supported by SQLite, MSSQL and PostgreSQL (in PostGIS extension).
knex.schema.createTable(tblName, (table) => {
table.geography('geographyColumn');
});
point
table.point(name)
添加点列。CockroachDB 和 MSSQL 不支持。
¥Add a point column. Not supported by CockroachDB and MSSQL.
knex.schema.createTable(tblName, (table) => {
table.point('pointColumn');
});
comment
table.comment(value)
设置表的注释。
¥Sets the comment for a table.
engine
table.engine(val)
设置数据库表的引擎,仅在 createTable 调用中可用,并且仅适用于 MySQL。
¥Sets the engine for the database table, only available within a createTable call, and only applicable to MySQL.
charset
table.charset(val)
设置数据库表的字符集,仅在 createTable 调用中可用,并且仅适用于 MySQL。
¥Sets the charset for the database table, only available within a createTable call, and only applicable to MySQL.
collate
table.collate(val)
设置数据库表的排序规则,仅在 createTable 调用中可用,并且仅适用于 MySQL。
¥Sets the collation for the database table, only available within a createTable call, and only applicable to MySQL.
inherits
table.inherits(val)
设置此表继承的表,仅在 createTable 调用中可用,并且仅适用于 PostgreSQL。
¥Sets the tables that this table inherits, only available within a createTable call, and only applicable to PostgreSQL.
specificType
table.specificType(name, type)
如果你想添加此处不支持的列类型,请为列创建设置特定类型。
¥Sets a specific type for the column creation, if you'd like to add a column type that isn't supported here.
index
table.index(columns, [indexName], options=({[indexType: string], [storageEngineIndexType: 'btree'|'hash'], [predicate: QueryBuilder]}))
在给定列的表中添加索引。除非指定了 indexName,否则将使用使用列的默认索引名称。在 MySQL 中,存储引擎索引类型可能是 'btree' 或 'hash' 索引类型,更多信息参见索引选项部分:https://dev.mysql.com/doc/refman/8.0/en/create-index.html。可以选择为 PostgreSQL 和 MySQL 指定 indexType。Amazon Redshift 不允许创建索引。在 PostgreSQL、SQLite 和 MSSQL 中,可以通过设置 'where' 谓词来指定部分索引。
¥Adds an index to a table over the given columns. A default index name using the columns is used unless indexName is specified. In MySQL, the storage engine index type may be 'btree' or 'hash' index types, more info in Index Options section : https://dev.mysql.com/doc/refman/8.0/en/create-index.html. The indexType can be optionally specified for PostgreSQL and MySQL. Amazon Redshift does not allow creating an index. In PostgreSQL, SQLite and MSSQL a partial index can be specified by setting a 'where' predicate.
knex.table('users', function (table) {
table.index(['name', 'last_name'], 'idx_name_last_name', {
indexType: 'FULLTEXT',
storageEngineIndexType: 'hash',
predicate: knex.whereNotNull('email'),
});
});
dropIndex
table.dropIndex(columns, [indexName])
从表中删除索引。除非指定了 indexName(在这种情况下,列将被忽略),否则将使用使用列的默认索引名称。Amazon Redshift 不允许创建索引。
¥Drops an index from a table. A default index name using the columns is used unless indexName is specified (in which case columns is ignored). Amazon Redshift does not allow creating an index.
setNullable
table.setNullable(column)
使表列可为空。
¥Makes table column nullable.
dropNullable
table.dropNullable(column)
使表列不可为空。请注意,如果此列中已存在空值,则此操作将失败。
¥Makes table column not nullable. Note that this operation will fail if there are already null values in this column.
primary
table.primary(columns, options=({[constraintName:string],[deferrable:'not deferrable'|'deferred'|'immediate']})
使用输入 columns
在表上创建主键约束。如果需要创建复合主键,请将列数组传递给 columns
。除非指定 constraintName
,否则约束名称默认为 tablename_pkey
。在 Amazon Redshift 上,主键中包含的所有列都不能为空。Postgres 和 Oracle 支持可延迟的主要约束,并且可以通过将可延迟选项传递给选项对象来设置。
¥Create a primary key constraint on table using input columns
. If you need to create a composite primary key, pass an array of columns to columns
. Constraint name defaults to tablename_pkey
unless constraintName
is specified. On Amazon Redshift, all columns included in a primary key must be not nullable. Deferrable primary constraint are supported on Postgres and Oracle and can be set by passing deferrable option to options object.
knex.schema.alterTable('users', function(t) {
t.unique('email')
})
knex.schema.alterTable('job', function(t) {
t.primary('email',{constraintName:'users_primary_key',deferrable:'deferred'})
})
信息
如果你想在创建新列时链接 primary(),你可以使用 primary
¥If you want to chain primary() while creating new column you can use primary
unique
table.unique(columns, options={[indexName: string], [deferrable:'not deferrable'|'immediate'|'deferred'], [storageEngineIndexType:'btree'|'hash'], [useConstraint:true|false], [predicate: QueryBuilder]})
在给定的 columns
上向表添加唯一索引。在 MySQL 中,存储引擎索引类型可能是 'btree' 或 'hash' 索引类型,更多信息参见索引选项部分:https://dev.mysql.com/doc/refman/8.0/en/create-index.html。除非指定了 indexName,否则将使用使用列的默认索引名称。如果需要创建复合索引,请将列数组传递给 columns
。Postgres 和 Oracle 支持可延迟唯一约束,可以通过将可延迟选项传递给选项对象来设置。在 MSSQL 和 Postgres 中,你可以将 useConstraint
选项设置为 true 以创建唯一约束而不是唯一索引(对于 MSSQL 默认为 false,对于不带 predicate
的 Postgres 默认为 true,对于带 predicate
的 Postgres 默认为 false)。在 PostgreSQL、SQLite 和 MSSQL 中,可以通过设置 'where' 谓词来指定部分唯一索引。
¥Adds an unique index to a table over the given columns
. In MySQL, the storage engine index type may be 'btree' or 'hash' index types, more info in Index Options section : https://dev.mysql.com/doc/refman/8.0/en/create-index.html. A default index name using the columns is used unless indexName is specified. If you need to create a composite index, pass an array of column to columns
. Deferrable unique constraint are supported on Postgres and Oracle and can be set by passing deferrable option to options object. In MSSQL and Postgres, you can set the useConstraint
option to true to create a unique constraint instead of a unique index (defaults to false for MSSQL, true for Postgres without predicate
, false for Postgres with predicate
). In PostgreSQL, SQLite and MSSQL a partial unique index can be specified by setting a 'where' predicate.
knex.schema.alterTable('users', function(t) {
t.unique('email')
})
knex.schema.alterTable('job', function(t) {
t.unique(['account_id', 'program_id'], {indexName: 'job_composite_index', deferrable: 'deferred', storageEngineIndexType: 'hash'})
})
knex.schema.alterTable('job', function(t) {
t.unique(['account_id', 'program_id'], {indexName: 'job_composite_index', useConstraint: true})
})
knex.schema.alterTable('job', function(t) {
t.unique(['account_id', 'program_id'], {indexName: 'job_composite_index', predicate: knex.whereNotNull('account_id')})
})
信息
如果你想在创建新列时链接 unique() ,你可以使用 unique
¥If you want to chain unique() while creating new column you can use unique
foreign
table.foreign(columns, [foreignKeyName])[.onDelete(statement).onUpdate(statement).withKeyName(foreignKeyName).deferrable(type)]
使用 table.foreign(column).references(column)
向表中的现有列或使用 table.foreign(columns).references(columns).inTable(table)
的多个列添加外键约束。
¥Adds a foreign key constraint to a table for an existing column using table.foreign(column).references(column)
or multiple columns using table.foreign(columns).references(columns).inTable(table)
.
除非指定 foreignKeyName
,否则将使用使用列的默认键名称。
¥A default key name using the columns is used unless foreignKeyName
is specified.
你还可以链接 onDelete()
和/或 onUpdate()
以设置操作的参考选项 (RESTRICT, CASCADE, SET NULL, NO ACTION)
。你还可以链接 withKeyName()
来覆盖从表名和列名生成的默认键名(结果与为函数 foreign()
指定第二个参数相同)。
¥You can also chain onDelete()
and/or onUpdate()
to set the reference option (RESTRICT, CASCADE, SET NULL, NO ACTION)
for the operation. You can also chain withKeyName()
to override default key name that is generated from table and column names (result is identical to specifying second parameter to function foreign()
).
Postgres 和 Oracle 支持可延迟的外部约束,可以通过链接 .deferrable(type)
来设置
¥Deferrable foreign constraint is supported on Postgres and Oracle and can be set by chaining .deferrable(type)
请注意,使用 foreign()
与 column.references(column)
相同,但它适用于现有列。
¥Note that using foreign()
is the same as column.references(column)
but it works for existing columns.
knex.schema.table('users', function (table) {
table.integer('user_id').unsigned()
table.foreign('user_id').references('Items.user_id_in_items').deferrable('deferred')
})
dropForeign
table.dropForeign(columns, [foreignKeyName])
从表中删除外键约束。除非指定了 foreignKeyName(在这种情况下忽略列),否则将使用使用列的默认外键名称。
¥Drops a foreign key constraint from a table. A default foreign key name using the columns is used unless foreignKeyName is specified (in which case columns is ignored).
dropUnique
table.dropUnique(columns, [indexName])
从表中删除唯一键约束。除非指定了 indexName(在这种情况下,列将被忽略),否则将使用使用列的默认唯一键名称。
¥Drops a unique key constraint from a table. A default unique key name using the columns is used unless indexName is specified (in which case columns is ignored).
dropPrimary
table.dropPrimary([constraintName])
删除表上的主键约束。除非指定了 constraintName,否则默认为 tablename_pkey。
¥Drops the primary key constraint on a table. Defaults to tablename_pkey unless constraintName is specified.
queryContext
table.queryContext(context)
允许配置要传递到 wrapIdentifier 钩子的上下文,以格式化表构建器标识符。上下文可以是任何类型的值,并且将不加修改地传递给 wrapIdentifier
。
¥Allows configuring a context to be passed to the wrapIdentifier hook for formatting table builder identifiers. The context can be any kind of value and will be passed to wrapIdentifier
without modification.
knex.schema.table('users', function (table) {
table.queryContext({ foo: 'bar' });
table.string('first_name');
table.string('last_name');
})
此方法还可以通过 schema.queryContext 覆盖为架构构建器实例配置的上下文:
¥This method also enables overwriting the context configured for a schema builder instance via schema.queryContext:
knex.schema.queryContext('schema context')
.table('users', function (table) {
table.queryContext('table context');
table.string('first_name');
table.string('last_name');
})
请注意,也可以覆盖表定义中任何列的表构建器上下文:
¥Note that it's also possible to overwrite the table builder context for any column in the table definition:
knex.schema.queryContext('schema context')
.table('users', function (table) {
table.queryContext('table context');
table.string('first_name').queryContext('first_name context');
table.string('last_name').queryContext('last_name context');
})
不带参数调用 queryContext
将返回为表构建器实例配置的任何上下文。
¥Calling queryContext
with no arguments will return any context configured for the table builder instance.
可链式的方法
¥Chainable Methods
以下三个方法可以链接到模式构建方法上,作为列的修饰符。
¥The following three methods may be chained on the schema building methods, as modifiers to the column.
alter
column.alter(options={[alterNullable: boolean = true, alterType: boolean = true])
将列标记为更改/修改,而不是默认添加。
¥Marks the column as an alter / modify, instead of the default add.
警告
这只适用于 .alterTable(),SQlite 或 Amazon Redshift 不支持。Alter 不会在较旧的列类型上增量完成,因此如果你想添加 notNullable
并保留旧的默认值,则 alter 语句必须同时包含 .notNullable().defaultTo(1).alter()
。如果只是尝试添加 .notNullable().alter()
,旧的默认值将被删除。仅当 alterNullable 为 true 时才会进行可空更改。仅当 alterType 为 true 时才会进行类型更改。
¥This only works in .alterTable() and is not supported by SQlite or Amazon Redshift. Alter is not done incrementally over older column type so if you like to add notNullable
and keep the old default value, the alter statement must contain both .notNullable().defaultTo(1).alter()
. If one just tries to add .notNullable().alter()
the old default value will be dropped. Nullable alterations are done only if alterNullable is true. Type alterations are done only if alterType is true.
knex.schema.alterTable('user', function(t) {
t.increments().primary(); // add
// drops previous default value from column,
// change type to string and add not nullable constraint
t.string('username', 35).notNullable().alter();
// drops both not null constraint and the default value
t.integer('age').alter();
// if alterNullable is false, drops only the default value
t.integer('age').alter({alterNullable : false});
// if alterType is false, type of column is not altered.
t.integer('age').alter({alterType : false});
});
index
column.index([indexName], options=({[indexType: string], [storageEngineIndexType: 'btree'|'hash'], [predicate: QueryBuilder]}))
指定一个字段作为索引。如果指定了 indexName,则使用它来代替标准索引命名约定 tableName_columnName。在 MySQL 中,存储引擎索引类型可能是 'btree' 或 'hash' 索引类型,更多信息参见索引选项部分:https://dev.mysql.com/doc/refman/8.0/en/create-index.html。可以选择为 PostgreSQL 和 MySQL 指定 indexType。如果它链接到无法索引的字段,则无操作。在 PostgreSQL、SQLite 和 MSSQL 中,可以通过设置 'where' 谓词来指定部分索引。
¥Specifies a field as an index. If an indexName is specified, it is used in place of the standard index naming convention of tableName_columnName. In MySQL, the storage engine index type may be 'btree' or 'hash' index types, more info in Index Options section : https://dev.mysql.com/doc/refman/8.0/en/create-index.html. The indexType can be optionally specified for PostgreSQL and MySQL. No-op if this is chained off of a field that cannot be indexed. In PostgreSQL, SQLite and MSSQL a partial index can be specified by setting a 'where' predicate.
primary
column.primary(options=({[constraintName:string],[deferrable:'not deferrable'|'deferred'|'immediate']}));
在 column
上设置主键约束。除非指定 constraintName
,否则约束名称默认为 tablename_pkey
。在 Amazon Redshift 上,主键中包含的所有列都不能为空。Postgres 和 Oracle 支持可延迟的主要约束,并且可以通过将可延迟选项传递给选项对象来设置。
¥Sets a primary key constraint on column
. Constraint name defaults to tablename_pkey
unless constraintName
is specified. On Amazon Redshift, all columns included in a primary key must be not nullable. Deferrable primary constraint are supported on Postgres and Oracle and can be set by passing deferrable option to options object.
knex.schema.table('users', function (table) {
table.integer('user_id').primary('email',{constraintName:'users_primary_key',deferrable:'deferred'})
})
unique
column.unique(options={[indexName:string],[deferrable:'not deferrable'|'immediate'|'deferred']})
将 column
设置为唯一。在 Amazon Redshift 上,不强制执行此约束,但查询规划器使用它。Postgres 和 Oracle 支持可延迟唯一约束,可以通过将可延迟选项传递给选项对象来设置。
¥Sets the column
as unique. On Amazon Redshift, this constraint is not enforced, but it is used by the query planner. Deferrable unique constraint are supported on Postgres and Oracle and can be set by passing deferrable option to options object.
knex.schema.table('users', function (table) {
table.integer('user_id').unique({indexName:'user_unique_id', deferrable:'immediate'})
})
references
column.references(column)
将当前列引用的 "column" 设置为外键。"column" 可以是 "." 语法,也可以只是列名,后面调用 inTable 来指定表。
¥Sets the "column" that the current column references as a foreign key. "column" can either be "." syntax, or just the column name followed up with a call to inTable to specify the table.
inTable
column.inTable(table)
调用 column.references 后设置外键列所在的 "table"。
¥Sets the "table" where the foreign key column is located after calling column.references.
onDelete
column.onDelete(command)
设置要运行的 SQL 命令 "onDelete"。
¥Sets the SQL command to be run "onDelete".
onUpdate
column.onUpdate(command)
设置要运行的 SQL 命令 "onUpdate"。
¥Sets the SQL command to be run "onUpdate".
defaultTo
column.defaultTo(value, options={[constraintName: string = undefined]))
设置插入时列的默认值。
¥Sets the default value for the column on an insert.
在 MSSQL 中,可以传递 constraintName 选项来确保特定的约束名称:
¥In MSSQL a constraintName option may be passed to ensure a specific constraint name:
column.defaultTo('value', { constraintName: 'df_table_value' });
unsigned
column.unsigned()
将数字指定为无符号。仅适用于数值。
¥Specifies a number as unsigned. Only for numeric values.
notNullable
column.notNullable()
在当前创建的列上添加非空值。
¥Adds a not null on the current column being created.
nullable
column.nullable()
默认情况下创建列时,这会显式地将字段设置为可为空。
¥Default on column creation, this explicitly sets a field to be nullable.
first
column.first()
设置要插入到第一个位置的列,仅在 MySQL alter table 中使用。
¥Sets the column to be inserted on the first position, only used in MySQL alter tables.
after
column.after(field)
设置要插入的列,仅在 MySQL alter table 中使用。
¥Sets the column to be inserted after another, only used in MySQL alter tables.
comment
column.comment(value)
设置列的注释。
¥Sets the comment for a column.
knex.schema.createTable('accounts', function(t) {
t.increments().primary();
t.string('email').unique().comment('This is the email field');
});
collate
column.collate(collation)
设置列的排序规则(仅适用于 MySQL)。以下是所有可用排序规则的列表:https://dev.mysql.com/doc/refman/5.5/en/charset-charsets.html
¥Sets the collation for a column (only works in MySQL). Here is a list of all available collations: https://dev.mysql.com/doc/refman/5.5/en/charset-charsets.html
knex.schema.createTable('users', function(t) {
t.increments();
t.string('email').unique().collate('utf8_unicode_ci');
});
视图
¥View
columns
view.columns([columnNames])
指定视图的列。
¥Specify the columns of the view.
knex.schema.createView('users_view', function (view) {
view.columns(['first_name', 'last_name']);
view.as(knex('users').select('first_name').where('age','>', '18'));
});
as
view.as(selectQuery)
指定视图的选择查询。
¥Specify the select query of the view.
checkOption
view.checkOption()
在视图定义上添加检查选项。在 OracleDb、MySQL、PostgreSQL 和 Redshift 上。
¥Add check option on the view definition. On OracleDb, MySQL, PostgreSQL and Redshift.
localCheckOption
view.localCheckOption()
在视图定义上添加本地检查选项。在 MySQL、PostgreSQL 和 Redshift 上。
¥Add local check option on the view definition. On MySQL, PostgreSQL and Redshift.
cascadedCheckOption
view.cascadedCheckOption()
在视图定义上添加级联检查选项。在 MySQL、PostgreSQL 和 Redshift 上。
¥Add cascaded check option on the view definition. On MySQL, PostgreSQL and Redshift.
检查
¥Checks
check
table.check(checkPredicate, [bindings], [constraintName]))
使用原始谓词指定对表或列的检查。
¥Specify a check on table or column with raw predicate.
knex.schema.createTable('product', function (table) {
table.integer('price_min');
table.integer('price');
table.check('?? >= ??', ['price', 'price_min']);
})
checkPositive
column.checkPositive([constraintName])
指定对列的检查,测试列的值是否为正。
¥Specify a check on column that test if the value of column is positive.
knex.schema.createTable('product', function (table) {
table.integer('price').checkPositive();
})
checkNegative
column.checkNegative([constraintName])
指定对列的检查,测试列的值是否为负数。
¥Specify a check on column that test if the value of column is negative.
knex.schema.createTable('product', function (table) {
table.integer('price_decrease').checkNegative();
})
checkIn
column.checkIn(values, [constraintName])
指定对列的检查,测试列的值是否包含在一组指定值中。
¥Specify a check on column that test if the value of column is contained in a set of specified values.
knex.schema.createTable('product', function (table) {
table.string('type').checkIn(['table', 'chair', 'sofa']);
})
checkNotIn
column.checkNotIn(values, [constraintName])
指定对列的检查,测试列的值是否不包含在一组指定值中。
¥Specify a check on column that test if the value of column is not contains in a set of specified values.
knex.schema.createTable('product', function (table) {
table.string('type').checkNotIn(['boot', 'shoe']);
})
checkBetween
column.checkBetween(values, [constraintName])
指定对列的检查,测试列的值是否在值范围内。
¥Specify a check on column that test if the value of column is within a range of values.
knex.schema.createTable('product', function (table) {
table.integer('price').checkBetween([0, 100]);
})
// You can add checks on multiple intervals
knex.schema.createTable('product', function (table) {
table.integer('price').checkBetween([ [0, 20], [30,40] ]);
})
checkLength
column.checkLength(operator, length, [constraintName])
指定对列的检查,以测试字符串的长度是否与谓词匹配。
¥Specify a check on column that test if the length of a string match the predicate.
knex.schema.createTable('product', function (table) {
// operator can be =, !=, <=, >=, <, >
t.varchar('phone').checkLength('=', 8);
})
checkRegex
column.checkRegex(regex, [constraintName])
指定对列的检查,以测试值是否与指定的正则表达式匹配。在 MSSQL 中,仅支持简单模式匹配,但不支持正则表达式语法。
¥Specify a check on column that test if the value match the specified regular expression. In MSSQL only simple pattern matching in supported but not regex syntax.
knex.schema.createTable('product', function (table) {
table.string('phone').checkRegex('[0-9]{8}');
// In MSSQL, {8} syntax don't work,
// you need to duplicate [0-9].
table.string('phone').checkRegex('[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]');
})
dropChecks
table.dropChecks([checkConstraintNames])
删除给定约束名称数组的检查约束。
¥Drop checks constraint given an array of constraint names.
knex.schema.createTable('product', function (table) {
table.integer('price').checkPositive('price_check')
table.integer('price_proportion').checkBetween([0, 100],'price_proportion_check')
table.dropChecks(['price_check', 'price_proportion_check']);
})