Search code examples
javascriptmysqlknex.js

How do you create a TINYINT column with Knex?


In the knex documentation, I only see the option to create an integer or biginteger.

For example, say I have a movies table with a rating column to store a movie's 5 star rating:

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

Is there a way to do this without resorting to a raw SQL query?


Solution

  • Although the answer of @Jumshud is a good alternative way to do it, here is the short answer:

    table.tinyint('rating');
    

    I dived into Knex 0.21.6 code and found a list of methods available that are not even documented in their website. In TableBuilder file knex/lib/schema/tablebuilder.js the is a list of methods injected into the Prototype of a PseudoClassical pattern TableBuilder. The methods are created for each columnTypes values:

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

    And the values of the columnTypes array are:

    // 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',
    ];
    

    Each value in this array is turned into a method in schema table builder.