我在 KnexJS 中使用 PostgreSQL 进行以下迁移时遇到问题:
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');
};
我使用 UUID
类型作为我的默认值,通过使用
defaultTo(knex.raw('uuid_generate_v4()'))
。
但是,在运行上述迁移时,通过:
knex migrate:latest --env development --knexfile knexfile.js --debug true
我得到一个错误:
function uuid_generate_v4() does not exist
你知道为什么knex.raw()
查询方法不起作用吗?
最佳答案
问题是你正在运行
knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"');
和
knex.schema.createTable('car_brands');
异步,所以第一个查询不会在第二个查询之前执行。
使用async/await
重写它:
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()'));
});
};
或使用Promises
:
exports.up = (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()'));
});
})
};
关于sql - 迁移中的 KnexJS 原始查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52969086/