Skip to content

fix: Generate binary_id values according to the binary_id_type config #72

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
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
11 changes: 11 additions & 0 deletions lib/ecto/adapters/sqlite3.ex
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,17 @@ defmodule Ecto.Adapters.SQLite3 do
end
end

@impl Ecto.Adapter.Schema
def autogenerate(:id), do: nil
def autogenerate(:embed_id), do: Ecto.UUID.generate()

def autogenerate(:binary_id) do
case Application.get_env(:ecto_sqlite3, :binary_id_type, :string) do
:string -> Ecto.UUID.generate()
:binary -> Ecto.UUID.bingenerate()
end
end

##
## Loaders
##
Expand Down
32 changes: 32 additions & 0 deletions test/ecto/adapters/sqlite3_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@ defmodule Ecto.Adapters.SQLite3Test do

alias Ecto.Adapters.SQLite3

@uuid_regex ~R/^[[:xdigit:]]{8}\b-[[:xdigit:]]{4}\b-[[:xdigit:]]{4}\b-[[:xdigit:]]{4}\b-[[:xdigit:]]{12}$/

setup do
original_binary_id_type = Application.get_env(:ecto_sqlite3, :binary_id_type)
on_exit(fn ->
Application.put_env(:ecto_sqlite3, :binary_id_type, original_binary_id_type)
end)
end

describe ".storage_up/1" do
test "create database" do
opts = [database: Temp.path!()]
Expand Down Expand Up @@ -51,4 +60,27 @@ defmodule Ecto.Adapters.SQLite3Test do
File.rm(opts[:database])
end
end

describe ".autogenerate/1" do
test ":id must be generated from storage" do
assert SQLite3.autogenerate(:id) == nil
end

test ":embed_id is a UUID in string form" do
assert string_uuid?(SQLite3.autogenerate(:embed_id))
end

test ":binary_id with type :string is a UUID in string form" do
Application.put_env(:ecto_sqlite3, :binary_id_type, :string)
assert string_uuid?(SQLite3.autogenerate(:binary_id))
end

test ":binary_id with type :binary is a UUID in binary form" do
Application.put_env(:ecto_sqlite3, :binary_id_type, :binary)
assert binary_uuid?(SQLite3.autogenerate(:binary_id))
end
end

defp string_uuid?(uuid), do: Regex.match?(@uuid_regex, uuid)
defp binary_uuid?(uuid), do: bit_size(uuid) == 128
end