KnexJS raw query in migration

Piot

New Member
#1
I have a problem with the following migration in KnexJS, working with PostgreSQL:
Mã:
exports.up = (knex) => {
    knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"');

    return knex.schema.createTable('car_brands', (table) => {
        table.uuid('brandId').unique().notNullable().primary().defaultTo(knex.raw('uuid_generate_v4()'));
        table.string('name').notNullable().unique();
        table.timestamp('created_at').notNullable().defaultTo(knex.raw('now()'));
        table.timestamp('updated_at').notNullable().defaultTo(knex.raw('now()'));
    });
};

exports.down = (knex) => {
    knex.raw('drop extension if exists "uuid-ossp"');
    return knex.schema.dropTable('car_brands');
};
I am using the UUID type for my default values, by using the
Mã:
defaultTo(knex.raw('uuid_generate_v4()'))
However, when running the above migration, by:
Mã:
knex migrate:latest --env development --knexfile knexfile.js --debug true
I get an error that:
Mã:
function uuid_generate_v4() does not exist
Do you know why the knex.raw() query method is not working?
 

Admin

Administrator
Thành viên BQT
#2
The problem is you are running
Mã:
knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"');
and
Mã:
knex.schema.createTable('car_brands');
asynchronously, so the first query is not executed before the second one.

Rewrite it using async/await:
Mã:
exports.up = async (knex) => {
    await knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"');

    return knex.schema.createTable('car_brands', (table) => {
        table.uuid('brandId').unique().notNullable().primary().defaultTo(knex.raw('uuid_generate_v4()'));
        table.string('name').notNullable().unique();
        table.timestamp('created_at').notNullable().defaultTo(knex.raw('now()'));
        table.timestamp('updated_at').notNullable().defaultTo(knex.raw('now()'));
    });
};
or using Promises:
Mã:
exports.up = async (knex) => {
    knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"')
        .then(() => {
            return knex.schema.createTable('car_brands', (table) => {
                table.uuid('brandId').unique().notNullable().primary().defaultTo(knex.raw('uuid_generate_v4()'));
                table.string('name').notNullable().unique();
                table.timestamp('created_at').notNullable().defaultTo(knex.raw('now()'));
                table.timestamp('updated_at').notNullable().defaultTo(knex.raw('now()'));
            });
        })
};
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top