Skip to content

Commit

Permalink
fix: Generate binary_id values according to the binary_id_type config (
Browse files Browse the repository at this point in the history
…#72)

* fix: Generate binary_id values according to the binary_id_type config
* fix: Preserve binary_id_type config value in-between tests
  • Loading branch information
Étienne Lévesque committed May 22, 2022
1 parent ca5f9dd commit ee43b00
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
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

0 comments on commit ee43b00

Please sign in to comment.