Search code examples
mysqlsqlknex.js

STRING, STRING(255) or VARCHAR (255)?


I use knex and have a MySql db table that was created with the following:

exports.up = function (knex, Promise) {
    return knex.schema.table("members", (table) => {
        table.string("member_activation_hash", 255);
        table.dateTime("member_activation_sent_at");
    });
};

Now I would like to change (only) the name of both columns, and was thinking of the following:

exports.up = function(knex) {
    return knex.schema.raw(
        "ALTER TABLE `members` CHANGE `member_activation_hash` `user_activation_hash` STRING DEFAULT NULL",
        "ALTER TABLE `members` CHANGE `member_activation_sent_at` `user_activation_sent_at` datetime DEFAULT NULL"
    );
};

But I'm not sure about STRING on line 3. When it was created it included 255 but I don't think STRING(255) is an option and VARCHAR(255) would change the data type (which I don't want). What would be the correct way to only change the name of member_activation_hash?

Update: So I now have:

exports.up = function(knex) {
    return knex.schema.raw(
        "ALTER TABLE `members` RENAME COLUMN `member_activation_hash` TO `user_activation_hash`",
        "ALTER TABLE `members` RENAME COLUMN `member_activation_sent_at` TO `user_activation_sent_at`"
    );
};

But this produces the error:

migration failed with error: Expected 1 bindings, saw 0 Error: Expected 1 bindings, saw 0 at replaceRawArrBindings (C:\Users\xxx\node_modules\knex\lib\raw.js:141:11) at Raw.toSQL (C:\Users\xxx\node_modules\knex\lib\raw.js:78:13)


Solution

  • Just rename the column:

    ALTER TABLE `members` RENAME COLUMN `member_activation_hash` TO `user_activation_hash`
    

    See the documentation here