I am running into an issue where Ecto seems to be padding white space to :char
fields when the length of the text is less than the allotted size. For instance I have a languages table where the primary key is the language code. Most of the time this is two characters, but it can be 3. Here is the relevant portion of the migration script.
create table(:languages, primary_key: false) do
add(:code, :char, primary_key: true, size: 3)
add(:name, :string, null: false)
add(:alternate_names, :map, null: false, default: %{})
timestamps()
end
And the schema:
@primary_key {:code, :string, autogenerate: false}
@foreign_key_type :string
@derive {Phoenix.Param, key: :code}
schema "languages" do
field(:name, :string)
field(:alternate_names, :map)
timestamps()
end
Inserting records seems to work as expected.
myapp_dev=# select code, LENGTH(code), name from languages where code = 'en';
code | length | name
------+--------+---------
en | 2 | English
(1 row)
myapp_dev=# select code, LENGTH(code), name from languages where code = 'arz';
code | length | name
------+--------+-----------------
arz | 3 | Egyptian Arabic
(1 row)
When I load the struct, two letter codes contain a trailing space. Notice the code: "en "
bit.
iex(21)> en = Myapp.Repo.get(Myapp.Language, "en")
[debug] QUERY OK source="languages" db=0.7ms queue=1.0ms idle=1415.7ms
SELECT l0."code", l0."name", l0."alternate_names", l0."inserted_at", l0."updated_at" FROM "languages" AS l0 WHERE (l0."code" = $1) ["en"]
âł anonymous fn/4 in :elixir.eval_external_handler/1, at: src/elixir.erl:312
%Myapp.Language{
__meta__: #Ecto.Schema.Metadata<:loaded, "languages">,
code: "en ",
name: "English",
alternate_names: %{},
inserted_at: ~N[2023-09-05 00:24:39],
updated_at: ~N[2023-09-05 00:24:39]
}
Is there any way to avoid this padding?
Thanks in advance!