postgresql - ActiveRecord:添加了 "uuid-ossp"扩展,但没有可用的 uuid 函数

标签 postgresql activerecord ruby-on-rails-5 postgresql-extensions

使用rails-5.0.7.1(根据bundle show rails)

我编写了一个迁移,其中添加了 "uuid-ossp" 扩展,并且执行 SQL,当我在 \dx 控制台中键入 psql 时,扩展会显示出来。但是,当我键入 uuid_generate_v4 时,此扩展提供的函数(例如 \df )不会显示,因此任何尝试使用应添加的函数都会失败。

当我从 ActiveRecord 迁移中获取 SQL 并将其直接复制并粘贴到 psql 控制台时,一切都按预期工作 - 添加了扩展,并且功能可用。

这是我的迁移代码:

class EnableUuidOssp < ActiveRecord::Migration[5.0]
  def up
    enable_extension "uuid-ossp"
  end

  def down
    disable_extension "uuid-ossp"
  end
end

这是输出:

$ bundle exec rake db:migrate
== 20190308113821 EnableUuidOssp: migrating ==============================
-- enable_extension("uuid-ossp")
   -> 0.0075s
== 20190308113821 EnableUuidOssp: migrated (0.0076s) =====================

^ 这一切似乎运行成功,但没有启用任何功能。这意味着包含诸如 ... SET uuid = uuid_generate_v4() ... 之类的语句的 future SQL 将失败并出现此错误 HINT: No function matches the given name and argument types. You might need to add explicit type casts.

什么有效

直接进入 psql 并输入:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

^ 这将安装扩展并使功能可用。

然而,什么不起作用

好吧,如果我采用上面的 SQL 并以这种方式重写我的迁移:

  ...

  def up
    execute <<~SQL
      CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
    SQL
  end

  ...

^ 此迁移将正常运行,但仍无法使功能可用。

因此,在 psql 中工作的相同复制+粘贴 SQL 无法通过 ActiveRecord execute 方法工作,这确实让我困惑。我不确定我错过了什么导致失败。

最佳答案

我假设安装扩展的架构不在您的 search_path 上。

您可以使用以下方式查看该架构

\dx "uuid-ossp"

尝试使用架构限定函数,例如 public.uuid_generate_v4()

关于postgresql - ActiveRecord:添加了 "uuid-ossp"扩展,但没有可用的 uuid 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55103723/

相关文章:

ruby-on-rails - SQLite3::ConstraintException: NOT NULL 约束失败: items.title: INSERT INTO "items"("image", "created_at", "updated_at") VALUES (?, ?, ?)

ruby-on-rails - 移动 Heroku 共享数据库

PostgreSQL:将列中的函数存储为值

postgresql - 如何在postgresql中动态创建触发器函数?

ruby-on-rails - rails多态关联中多列索引的顺序

ruby-on-rails - Rails STI 覆盖范围

mysql - Rails 4 ActiveRecord 按关联计数排序

javascript - 如何使用 Actioncable 创建多个 channel ;如何将文档内变量传递给 javascript 和 ruby​​ channel 和作业?

ruby-on-rails - Ruby on rails 测试 - 表 X 没有名为 Y 的列

postgresql - 外键定义中的列顺序重要吗?