【问题标题】:Add function to sqlite3 using knex, bookshelf使用 knex、书架向 sqlite3 添加函数
【发布时间】:2017-05-21 23:35:52
【问题描述】:

我在开发范围内使用 postgresql,它有函数调用“uuid_generate_v4()” 在测试范围内,我使用 sqlite3,但迁移代码不起作用,因为缺少“uuid_generate_v4()”。 那么我可以解决这个问题吗?

connection.schema.createTableIfNotExists('notification', (table) => {
  // UUID
  table.uuid('id').primary().defaultTo(connection.raw('uuid_generate_v4()'))

  // Adds a "created_at" and "updated_at" columns on the database,
  // setting these each to "dateTime" types.
  table.timestamps()

  table.string('type', 255)

  table.string('summary', 255)

  table.string('text', 255)

  table.string('actionText', 255)

  table.string('actionUrl', 255)

  table.uuid('recipient').references('user.id')
}),

“如果不存在则创建表”失败“通知”(“id”char(36)默认uuid_generate_v4(),“created_at”日期时间,“updated_at”日期时间,“type”varchar(255),“summary”varchar( 255), "text" varchar(255), "actionText" varchar(255), "actionUrl" varchar(255), "recipient" char(36), 外键("recipient") 引用 "user"("id" ), 主键 ("id")) - SQLITE_ERROR: near "(": 语法错误"

【问题讨论】:

  • 将您的测试环境切换到 PostgreSQL。使用不同的数据库进行开发和测试有点违背测试的目的。
  • 我知道这一点,但我想要求解决 sqlite3 中的使用函数以在任何地方使用:)
  • 如果您将失败的迁移代码添加到问题中,则更容易回答如何在那里添加 SQL 方言特定实现,以便它为 sqlite 生成不同的 uuid。
  • 是的,我添加了代码和错误。那么你有解决方案吗?
  • 在代码中生成 UUID,而不是让数据库来做。但这是最小的问题,SQLite 和 PostgreSQL 之间有很多差异,坦率地说,使用 SQLite 运行测试是愚蠢的。

标签: node.js sqlite knex.js bookshelf.js


【解决方案1】:

正如@mu-is-too-short 评论的那样,无论如何我不建议这样做,但可以这样做:

let uuidGenerationRaw = connection.client.config.client === 'sqlite3' ? 
  `(lower(hex(randomblob(4))) || '-' || lower(hex(randomblob(2))) || '-4' || substr(lower(hex(randomblob(2))),2) || '-' || substr('89ab',abs(random()) % 4 + 1, 1) || substr(lower(hex(randomblob(2))),2) || '-' || lower(hex(randomblob(6))))` :
  `uuid_generate_v4()`;

connection.schema.createTableIfNotExists('notification', (table) => {
  table.uuid('id').primary().defaultTo(connection.raw(uuidGenerationRaw));
  // ... rest of the columns
}),

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多