您需要爲每個postgresql枚舉創建一個Ecto類型。在架構定義中,只需鍵入:string
即可。在遷移中,您將類型設置爲模塊名稱。這可以變得很繁瑣,雖然如此,我在我的項目下面的宏使用PostgreSQL的枚舉:
defmodule MyDB.Enum do
alias Postgrex.TypeInfo
defmacro defenum(module, name, values, opts \\ []) do
quote location: :keep do
defmodule unquote(module) do
@behaviour Postgrex.Extension
@typename unquote(name)
@values unquote(values)
def type, do: :string
def init(_params, opts), do: opts
def matching(_), do: [type: @typename]
def format(_), do: :text
def encode(%TypeInfo{type: @typename}=typeinfo, str, args, opts) when is_atom(str), do: encode(typeinfo, to_string(str), args, opts)
def encode(%TypeInfo{type: @typename}, str, _, _) when str in @values, do: to_string(str)
def decode(%TypeInfo{type: @typename}, str, _, _), do: str
def __values__(), do: @values
defoverridable init: 2, matching: 1, format: 1, encode: 4, decode: 4
unquote(Keyword.get(opts, :do, []))
end
end
end
end
可能的用法:
import MyDB.Enum
defenum ColorsEnum, "colors_enum", ~w"blue red yellow"
ColorsEnum
將是模塊名稱,"colors_enum"
將是Postgresql內部的枚舉名稱:您將需要添加一條語句以在您的數據庫遷移中創建枚舉類型。最後一個參數是一個枚舉值列表。我使用了一個~w
sigil,它將用空格分隔字符串,以顯示這可能是多麼簡潔。我還添加了一個子句,它在通過Ecto模式時將原子值轉換爲字符串值。
看起來像'ecto_enum'不再維護 – ryanwinchester