【问题标题】:Adding default to binary type in Ecto for Postgres [Elixir]在 Ecto for Postgres [Elixir] 中为二进制类型添加默认值
【发布时间】:2020-06-12 14:45:01
【问题描述】:

在体外迁移期间尝试设置默认值时遇到了令人沮丧的问题

在迁移中,代码如下所示:

def encode(binary) do
  "\\x" <> Base.encode16(binary, case: :lower)
end

Logger.debug("admin.id = #{inspect admin.id}")
Logger.debug("admin.id = #{inspect UUID.string_to_binary!(admin.id)}")
Logger.debug("admin.id = #{inspect encode(admin.id)}")

alter table(@questions) do
  add :owner_id, references(:users, on_delete: :nothing, type: :binary_id), null: false, default: admin.id
end

你可以在记录器中看到我上面尝试过的尝试

我得到了错误

default values are interpolated as UTF-8 strings and cannot contain null bytes. `<<209, 241, 
149, 133, 44, 81, 70, 164, 181, 120, 214, 0, 253, 191, 198, 214>>` is invalid. If you want 
to write it as a binary, use "\xd1f195852c5146a4b578d600fdbfc6d6", otherwise refer to 
PostgreSQL documentation for instructions on how to escape this SQL type

任何帮助都会非常感谢

【问题讨论】:

    标签: postgresql migration elixir uuid ecto


    【解决方案1】:

    :binary_id 与 Postgres 一起使用时,Ecto 期望您将 UUID 作为字符串传递。您的错误消息表明您尝试将其作为二进制文件传递,因此您应该首先将其转换为字符串:

    add :owner_id, references(:users, on_delete: :nothing, type: :binary_id), null: false, default: UUID.binary_to_string!(admin.id)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-09
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多