Pio*_*rCh 3 sql postgresql node.js knex.js
我在使用 PostgreSQL 的 KnexJS 中进行以下迁移时遇到问题:
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');
};
Run Code Online (Sandbox Code Playgroud)
我使用该UUID类型作为我的默认值,通过使用
defaultTo(knex.raw('uuid_generate_v4()')).
但是,在运行上述迁移时,通过:
knex migrate:latest --env development --knexfile knexfile.js --debug true
Run Code Online (Sandbox Code Playgroud)
我收到一个错误:
function uuid_generate_v4() does not exist
Run Code Online (Sandbox Code Playgroud)
你知道为什么knex.raw()查询方法不起作用吗?
Iho*_*yuk 11
问题是你正在运行
knex.raw('CREATE EXTENSION IF NOT EXISTS "uuid-ossp"');
Run Code Online (Sandbox Code Playgroud)
和
knex.schema.createTable('car_brands');
Run Code Online (Sandbox Code Playgroud)
异步,因此第一个查询不会在第二个查询之前执行。
使用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()'));
});
};
Run Code Online (Sandbox Code Playgroud)
或使用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()'));
});
})
};
Run Code Online (Sandbox Code Playgroud)