的knex.schema是一个吸气函数,返回包含所述查询的状态的对象。因此,请确保knex.schema为每个查询获取一个新的实例。这些方法返回promise。


withSchema —knex.schema.withSchema([schemaName])

指定在使用schema-building命令时要使用的架构。


knex.schema.withSchema('public').createTable('users', function (table) {

  table.increments();

})

输出:

create table `public`.`users` (`id` int unsigned not null auto_increment primary key)

createTable —knex.schema.createTable(tableName, callback)

使用schema-building命令在数据库上创建一个新表,并使用回调函数来修改表的结构。


knex.schema.createTable('users', function (table) {

  table.increments();

  table.string('name');

  table.timestamps();

})

输出:

create table `users` (`id` int unsigned not null auto_increment primary key, `name` varchar(255), `created_at` datetime, `updated_at` datetime)

namedTable —knex.schema.renameTable(from, to)

将表从当前tableName重命名为另一个。


knex.schema.renameTable('users', 'old_users')

输出:

rename table `users` to `old_users`

dropTable —knex.schema.dropTable(tableName)

删除由tableName指定的表。


knex.schema.dropTable('users')

输出:

drop table `users`

hasTable —knex.schema.hasTable(tableName)

通过tableName检查表是否存在,并使用布尔值解析以表示该表是否存在。


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。


dropTableIfExists —knex.schema.dropTableIfExists(tableName)

如果表存在,则有条件地删除表,该表由tableName指定。


knex.schema.dropTableIfExists('users')

输出:

drop table if exists `users`

表 —knex.schema.table(tableName, callback)

选择一个数据库表,然后使用回调内部的“模式构建”功能修改该表。


knex.schema.table('users', function (table) {

  table.dropColumn('name');

  table.string('first_name');

  table.string('last_name');

})

输出:

alter table `users` add `first_name` varchar(255), add `last_name` varchar(255);

alter table `users` drop `name`

原始 —knex.schema.raw(statement)

在架构构建器链中运行任意sql查询。


knex.schema.raw("SET sql_mode='TRADITIONAL'")

  .table('users', function (table) {

    table.dropColumn('name');

    table.string('first_name');

    table.string('last_name');

  })

输出:

SET sql_mode='TRADITIONAL';

alter table `users` add `first_name` varchar(255), add `last_name` varchar(255);

alter table `users` drop `name`

queryContext —knex.schema.queryContext(context)

允许配置上下文以传递给wrapIdentifier挂钩。上下文可以是任何类型的值,并且将直接传递给它们wrapIdentifier而无需修改。


knex.schema.queryContext({ foo: 'bar' })

  .table('users', function (table) {

    table.string('first_name');

    table.string('last_name');

  })

将为wrapIdentifier需要格式化的每个标识符(包括表名和列名)将配置的上下文传递给。但是,可以通过table.queryContext为列名设置不同的上下文。


queryContext不带参数的调用将返回为架构构建器实例配置的任何上下文。


模式构建:

dropColumn —table.dropColumn(name)

删除由列名指定的列


dropColumns —table.dropColumns(*columns)

删除多个列,采用可变数量的列名。


namedColumn —table.renameColumn(from, to)

将列从一个名称重命名为另一个。


增量 —table.increments(name)

添加一个自动递增列。在PostgreSQL中,这是一个序列。在Amazon Redshift中为整数标识(1,1)。这将用作表的主键。如果您想添加bigint递增数字(在PostgreSQL bigserial中),也可以使用bigIncrements。


// create table 'users' with a primary key using 'increments()'

knex.schema.createTable('users', function (table) {

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

});

整数 —table.integer(name)

添加一个整数列。


bigInteger —table.bigInteger(name)

在MySQL或PostgreSQL中,添加一个bigint列,否则添加一个普通整数。请注意,bigint数据在查询中以字符串形式返回,因为JavaScript可能无法解析它们而不损失精度。


文字 -table.text(name, [textType])

添加文本列,并为MySql文本数据类型首选项提供可选的textType。textType可以是mediumtext或longtext,否则默认为text。


字符串 —table.string(name, [length])

添加一个字符串列,其可选长度默认为255。


浮动 -table.float(column, [precision], [scale])

添加一个具有可选精度(默认为8)和小数位数(默认为2)的浮点列。


十进制 -table.decimal(column, [precision], [scale])

添加具有可选精度(默认为8)和小数位数(默认为2)的十进制列。将NULL指定为精度会创建一个十进制列,该列可以存储任意精度和小数位数。(仅支持Oracle,SQLite,Postgres)


布尔值 -table.boolean(name)

添加一个布尔列。


日期 -table.date(name)

添加日期列。


日期时间 -table.datetime(name, options={[useTz: boolean], [precision: number]})

添加日期时间列。默认情况下,PostgreSQL创建带有时区(timestamptz类型)的列。可以通过传递useTz选项(对于PostgreSQL默认为true)来覆盖此行为。MySQL和MSSQL没有useTz选项。


可以传递精度选项:


table.datetime('some_time', { precision: 6 }).defaultTo(knex.fn.now(6))

时间 -table.time(name, [precision])

添加一个时间列,对于MySQL具有可选的精度。Amazon Redshift不支持。


在MySQL中,可以传递精度选项:


table.time('some_time', { precision: 6 })

时间戳记 —table.timestamp(name, options={[useTz: boolean], [precision: number]})

添加一个时间戳列。默认情况下,PostgreSQL使用时区(timestamptz类型)创建列,而MSSQL不创建(datetime2)。可以通过传递useTz选项来覆盖此行为(默认情况下,对于MSSQL为false,对于PostgreSQL为true)。MySQL没有useTz选项。


table.timestamp('created_at').defaultTo(knex.fn.now());

在PostgreSQL和MySQL中,可以传递precision选项:


table.timestamp('created_at', { precision: 6 }).defaultTo(knex.fn.now(6));

在PostgreSQL和MSSQL中,可以传递时区选项:


table.timestamp('created_at', { useTz: true });

时间戳记 —table.timestamps([useTimestamps], [defaultToNow])

在数据库上添加created_at和updated_at列,并将每个列设置为日期时间类型。当将true作为第一个参数传递时,将使用时间戳记类型。两个列默认都不为null,并且在将true作为第二个参数传递时使用当前时间戳。请注意,在MySQL上,.timestamps()的精度仅为秒,要获得更好的精度,请直接使用.datetime或.timestamp方法。


dropTimestamps —table.dropTimestamps()

从表中删除创建的列和更新的列,可以通过时间戳创建列。


二进制 -table.binary(name, [length])

添加一个二进制列,对于MySQL具有可选的length参数。


枚举/枚举 —table.enu(col, values, [options])

添加一个enum列(别名为enu,因为enum是JavaScript中的保留字)。在Amazon Redshift上实现为未经检查的varchar(255)。请注意,第二个参数是一个值数组。例:


table.enu('column', ['value1', 'value2'])

对于Postgres,可以提供一个附加的options参数来指定是否使用Postgres的本机TYPE:


table.enu('column', ['value1', 'value2'], { useNative: true, enumName: 'foo_type' })

它将使用提供的值来生成适当的TYPE。例:


CREATE TYPE "foo_type" AS ENUM ('value1', 'value2');

要在各列之间使用现有的本机类型,请在选项中指定“ existingType”(假定该类型已创建):


注意:由于本机&&现有类型未使用枚举值,因此传入值的类型无关紧要。


table.enu('column', null, { useNative: true, existingType: true, enumName: 'foo_type' })

如果要使用与当前表的架构不同的架构中的现有枚举,请在选项中指定“ schemaName”:


table.enu('column', null, { useNative: true, existingType: true, enumName: 'foo_type', schemaName: 'public' })

json —table.json(name)

使用PostgreSQL,MySQL和SQLite中的内置json类型添加一个json列,默认为旧版本或不受支持的数据库中的text列。


对于PostgreSQL,由于本机数组与json类型之间不兼容,因此在将数组(或可能是数组的值)设置为json或jsonb列的值时,应使用JSON.stringify()将值转换为将字符串传递给查询构建器之前的字符串,例如


knex.table('users')

  .where({id: 1})

  .update({json_data: JSON.stringify(mightBeAnArray)});

jsonb —table.jsonb(name)

添加一个jsonb列。与table.json()相似,但尽可能使用本机jsonb类型。


uuid —table.uuid(name)

添加一个uuid列-使用PostgreSQL中的内置uuid类型,并回退到其他数据库中的char(36)。


评论 —table.comment(value)

设置表的注释。


引擎 —table.engine(val)

设置数据库表的引擎,仅在createTable调用中可用,并且仅适用于MySQL。


字符集 -table.charset(val)

设置数据库表的字符集,仅在createTable调用中可用,并且仅适用于MySQL。


整理 —table.collate(val)

设置数据库表的排序规则,仅在createTable调用中可用,并且仅适用于MySQL。


继承 -table.inherits(val)

设置该表继承的表,仅在createTable调用中可用,并且仅适用于PostgreSQL。


specificType —table.specificType(name, type)

如果要添加此处不支持的列类型,请为列创建设置特定类型。


索引 -table.index(columns, [indexName], [indexType])

在给定列上向表添加索引。除非指定indexName,否则使用使用列的默认索引名称。可以为PostgreSQL和MySQL指定indexType。Amazon Redshift不允许创建索引。


dropIndex —table.dropIndex(columns, [indexName])

从表中删除索引。除非指定indexName,否则使用使用列的默认索引名(在这种情况下,将忽略列)。Amazon Redshift不允许创建索引。


独特的 -table.unique(columns, [indexName])

在给定的表中添加唯一索引columns。除非指定indexName,否则使用使用列的默认索引名称。


knex.schema.alterTable('users', function(t) {

  t.unique('email')

})

knex.schema.alterTable('job', function(t) {

  t.unique(['account_id', 'program_id'])

})

外国 —table.foreign(columns, [foreignKeyName])[.onDelete(statement).onUpdate(statement).withKeyName(foreignKeyName)]

为使用的现有列table.foreign(column).references(column)或使用的多个列向表添加外键约束table.foreign(columns).references(columns).inTable(table)。除非指定了foreignKeyName,否则将使用使用列的默认键名。您还可以链接onDelete()和/或onUpdate()来设置操作的引用选项(RESTRICT,CASCADE,SET NULL,NO ACTION)。您也可以与withKeyName()链接以覆盖由表名和列名生成的默认键名(结果与为函数foreign()指定第二个参数相同)。请注意,使用foreign()与column.references(column)相同,但适用于现有的列。


knex.schema.table('users', function (table) {

  table.integer('user_id').unsigned()

  table.foreign('user_id').references('Items.user_id_in_items')

})

dropForeign —table.dropForeign(columns, [foreignKeyName])

从表中删除外键约束。除非指定了foreignKeyName,否则使用使用列的默认外键名称(在这种情况下,将忽略列)。


dropUnique —table.dropUnique(columns, [indexName])

从表中删除唯一键约束。除非指定了indexName,否则使用使用列的默认唯一键名称(在这种情况下,将忽略列)。


dropPrimary —table.dropPrimary([constraintName])

在表上删除主键约束。除非指定constraintName,否则默认为tablename_pkey。


queryContext —table.queryContext(context)

允许配置上下文以传递给wrapIdentifier挂钩,以格式化表构建器标识符。上下文可以是任何类型的值,并且将直接传递给它们wrapIdentifier而无需修改。


knex.schema.table('users', function (table) {

  table.queryContext({ foo: 'bar' });

  table.string('first_name');

  table.string('last_name');

})

此方法还可以通过schema.queryContext覆盖为架构构建器实例配置的上下文:


knex.schema.queryContext('schema context')

  .table('users', function (table) {

    table.queryContext('table context');

    table.string('first_name');

    table.string('last_name');

})

注意,还可以覆盖表定义中任何列的表构建器上下文:


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不带参数的调用将返回为表构建器实例配置的任何上下文。


可链接方法:

可以将以下三种方法链接到架构构建方法上,作为对列的修改器。


改变 —column.alter()

将列标记为更改/修改,而​​不是默认添加。注意:这仅适用于.alterTable(),SQlite或Amazon Redshift不支持。Alter 不会对较旧的列类型进行增量处理,因此,如果您想添加notNull并保留旧的默认值,则alter语句必须包含二者.notNull().defaultTo(1).alter()。如果只是尝试添加.notNull().alter()旧的默认值将被删除。


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

});

索引 -column.index([indexName], [indexType])

指定一个字段作为索引。如果指定了indexName,它将代替tableName_columnName的标准索引命名约定。可以为PostgreSQL和MySQL指定indexType。如果此操作链接到无法索引的字段,则为No-op。


主要 -column.primary([constraintName]); table.primary(columns, [constraintName])

在单列上调用时,它将将该列设置为表的主键。如果需要创建复合主键,请在具有列名称数组的表上调用它。约束名称默认为tablename_pkey除非constraintName指定。在Amazon Redshift上,主键中包含的所有列都不能为空。


独特的 -column.unique()

将列设置为唯一。在Amazon Redshift上,不强制执行此约束,但查询计划者会使用它。


参考 —column.references(column)

将当前列引用的“列”设置为外键。“列”可以是“。语法,或者只是列名,然后调用inTable来指定表。


inTable —column.inTable(table)

在调用column.references之后设置外键列所在的“表”。


onDelete —column.onDelete(command)

将SQL命令设置为“ onDelete”运行。


onUpdate —column.onUpdate(command)

将SQL命令设置为“ onUpdate”运行。


defaultTo —column.defaultTo(value)

为插入项上的列设置默认值。


未签名 -column.unsigned()

将整数指定为无符号。如果这是从非整数字段中链接出来的,则为No-op。


notNullable —column.notNullable()

在正在创建的当前列上添加一个非空值。


可为空 —column.nullable()

列创建时的默认设置,这将字段显式设置为可为空。


首先 -column.first()

设置要在第一个位置插入的列,仅在MySQL alter table中使用。


之后 -column.after(field)

设置要插入的列,仅在MySQL alter table中使用。


评论 —column.comment(value)

设置列的注释。


knex.schema.createTable('accounts', function(t) {

  t.increments().primary();

  t.string('email').unique().comment('This is the email field');

});

整理 —column.collate(collation)

设置列的排序规则(仅在MySQL中有效)。这是所有可用排序规则的列表: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');

});