如何使用 Knex 创建 TINYINT 列?

How do you create a TINYINT column with Knex?

knex documentation 中,我只看到创建整数或双整数的选项。

例如,假设我有一个 movies table 和一个 rating 列来存储电影的 5 星评级:

// Migration script

exports.up = knex => {
  return knex.schema
    .createTable('movies', table => {
      table.uuid('id').primary()
      ...
      table.integer('rating') // <-- I want this to be a TINYINT
    })
}

有没有一种方法可以在不诉诸原始 SQL 查询的情况下做到这一点?

您可以使用 specificType 如下:

table.specificType('rating', 'tinyint(1)')

虽然@Jumshud 的回答是一个很好的替代方法,但这里是简短的回答:

table.tinyint('rating');

我深入研究了 Knex 0.21.6 代码,发现了一个可用方法列表,这些方法甚至没有记录在他们的网站上。在 TableBuilder 文件 knex/lib/schema/tablebuilder.js 中,这是一个注入到 PseudoClassical 模式 TableBuilder 原型中的方法列表。这些方法是为每个 columnTypes 个值创建的:

// For each of the column methods, create a new "ColumnBuilder" interface,
// push it onto the "allStatements" stack, and then return the interface,
// with which we can add indexes, etc.
each(columnTypes, function (type) {
  TableBuilder.prototype[type] = function () {
    const args = toArray(arguments);
    const builder = this.client.columnBuilder(this, type, args);
    this._statements.push({
      grouping: 'columns',
      builder,
    });
    return builder;
  };
});

columnTypes 数组的值为:

// Each of the column types that we can add, we create a new ColumnBuilder
// instance and push it onto the statements array.
const columnTypes = [
  // Numeric
  'tinyint',
  'smallint',
  'mediumint',
  'int',
  'bigint',
  'decimal',
  'float',
  'double',
  'real',
  'bit',
  'boolean',
  'serial',

  // Date / Time
  'date',
  'datetime',
  'timestamp',
  'time',
  'year',

  // String
  'char',
  'varchar',
  'tinytext',
  'tinyText',
  'text',
  'mediumtext',
  'mediumText',
  'longtext',
  'longText',
  'binary',
  'varbinary',
  'tinyblob',
  'tinyBlob',
  'mediumblob',
  'mediumBlob',
  'blob',
  'longblob',
  'longBlob',
  'enum',
  'set',

  // Increments, Aliases, and Additional
  'bool',
  'dateTime',
  'increments',
  'bigincrements',
  'bigIncrements',
  'integer',
  'biginteger',
  'bigInteger',
  'string',
  'json',
  'jsonb',
  'uuid',
  'enu',
  'specificType',
];

此数组中的每个值都转换为模式 table 构建器中的一个方法。

如果有人需要使用tinyint作为布尔值(TINYINT(1)),可以使用table.boolean()方法。