简体   繁体   中英

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

I'm having a frustrating issue trying to set a default during an ecto migration

In the migration the code looks like the following:

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

You can see the attempts I tried above in the logger

I get the error

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

Any help would be great thanks

When using :binary_id with Postgres, Ecto expects you to pass UUIDs as strings. Your error message implies you tried to pass it as a binary, so you should first convert it to a string:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM