sql - 迁移中的 KnexJS 原始查询

标签 sql node.js postgresql knex.js

我在 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/

相关文章:

c# - 在异常中捕获 "happy path"是一种不好的做法吗?

javascript - 使用 res.send 返回成功

postgresql/pgAdmin - 服务器不监听问题

python - Postgres 用户未连接到数据库。即使环境变量设置正确

sql - 使用 Anorm 和 Scala Play 框架的动态 SQL 参数

mysql - 如何在 Select 语句中使用千位分隔符显示列?

node.js - 得到错误 TS2304 : Cannot find name 'Buffer'

postgresql - Docker volume 不持久化数据

sql - 什么时候引用完整性不合适?

node.js - NPM 安装错误本地存储库的权限被拒绝(公钥)