Skip to content

allow binary type #32

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ TypeIDs as fields in your Ecto schemas.
defmodule MyApp.Accounts.User do
use Ecto.Schema

@primary_key {:id, TypeID, autogenerate: true, prefix: "acct", type: :binary_id}
@primary_key {:id, TypeID, autogenerate: true, prefix: "acct", type: :binary}
@foreign_key_type TypeID

# ...
Expand All @@ -40,15 +40,15 @@ end

### Underlying types

`TypeID`s can be stored as either `:string` or `:binary_id`. `:string` will
store the entire TypeID including the prefix. `:binary_id` stores only the
UUID portion and requires a `:uuid` or `:binary` column.
`TypeID`s can be stored as either `:string` or `:binary`. `:string` will store
the entire TypeID including the prefix. `:binary` stores only the UUID portion
and requires a `:uuid` or `:binary` column.

#### Default type

The type used can be set globally in the application config.

```elixir
config :typeid_elixir,
default_type: :binary_id
default_type: :binary
```
10 changes: 5 additions & 5 deletions lib/type_id/ecto.ex
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ if Code.ensure_loaded?(Ecto.ParameterizedType) do

case {tid.prefix, type} do
{^prefix, :string} -> {:ok, TypeID.to_string(tid)}
{^prefix, :binary_id} -> {:ok, TypeID.uuid(tid)}
{^prefix, :binary} -> {:ok, TypeID.uuid_bytes(tid)}
_ -> :error
end
end
Expand All @@ -66,12 +66,12 @@ if Code.ensure_loaded?(Ecto.ParameterizedType) do
end
end

def load(<<_::128>> = uuid, _, %{type: :binary_id} = params) do
def load(<<_::128>> = uuid, _, %{type: :binary} = params) do
prefix = find_prefix(params)
TypeID.from_uuid_bytes(prefix, uuid)
end

def load(<<_::288>> = uuid, _, %{type: :binary_id} = params) do
def load(<<_::288>> = uuid, _, %{type: :binary} = params) do
prefix = find_prefix(params)
TypeID.from_uuid(prefix, uuid)
rescue
Expand All @@ -95,8 +95,8 @@ if Code.ensure_loaded?(Ecto.ParameterizedType) do
end
end

unless type in ~w[string binary_id]a do
raise ArgumentError, "`type` must be `:string` or `:binary_id`"
unless type in ~w[string binary]a do
raise ArgumentError, "`type` must be `:string` or `:binary`"
end

if primary_key do
Expand Down
Loading