在 Ecto for Postgres [Elixir] 中为二进制类型添加默认值

Adding default to binary type in Ecto for Postgres [Elixir]

我在尝试在外迁移过程中设置默认值时遇到了一个令人沮丧的问题

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

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

如有帮助将不胜感激

在 Postgres 中使用 :binary_id 时,Ecto 希望您将 UUID 作为字符串传递。您的错误消息暗示您试图将其作为二进制文件传递,因此您应该首先将其转换为字符串:

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