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

问题描述 投票:0回答:1

我在尝试迁移时尝试设置默认值时遇到令人沮丧的问题

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

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个回答
0
投票

与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)
© www.soinside.com 2019 - 2024. All rights reserved.