Page MenuHomePhorge

compat_type.ex
No OneTemporary

Size
1 KB
Referenced Files
None
Subscribers
None

compat_type.ex

# FlakeId: Decentralized, k-ordered ID generation service
# Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
# SPDX-License-Identifier: LGPL-3.0-only
defmodule FlakeId.Ecto.CompatType do
@moduledoc """
Provides a compatibility Ecto type for someone wishes to migrate from integer ids to flakes.
## Schema Example
@primary_key {:id, FlakeId.Ecto.CompatType, autogenerate: true}
schema "posts" do
add :body, :string
end
"""
import Kernel, except: [to_string: 1]
@behaviour Ecto.Type
def embed_as(_), do: :self
def equal?(term1, term2), do: term1 == term2
def type, do: :uuid
defdelegate autogenerate, to: FlakeId, as: :get
def cast(value) do
{:ok, to_string(value)}
end
def load(value) do
{:ok, to_string(value)}
end
def dump(value) do
{:ok, from_string(value)}
end
defp to_string(<<0::integer-size(64), id::integer-size(64)>>), do: Kernel.to_string(id)
defp to_string(binary_flake), do: FlakeId.to_string(binary_flake)
# zero or -1 is a null flake
for i <- [-1, 0] do
defp from_string(unquote(i)), do: <<0::integer-size(128)>>
defp from_string(unquote(Kernel.to_string(i))), do: <<0::integer-size(128)>>
end
defp from_string(int) when is_integer(int) do
int
|> Kernel.to_string()
|> from_string()
end
defp from_string(<<_::integer-size(128)>> = flake), do: flake
defp from_string(string) when is_binary(string) and byte_size(string) < 18 do
case Integer.parse(string) do
{id, ""} -> <<0::integer-size(64), id::integer-size(64)>>
_ -> nil
end
end
defp from_string(string), do: FlakeId.from_string(string)
end

File Metadata

Mime Type
text/x-ruby
Expires
Tue, Jan 21, 11:09 AM (1 d, 3 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
55708
Default Alt Text
compat_type.ex (1 KB)

Event Timeline