Skip to content

Commit ee43b00

Browse files
author
Étienne Lévesque
authored
fix: Generate binary_id values according to the binary_id_type config (#72)
* fix: Generate binary_id values according to the binary_id_type config * fix: Preserve binary_id_type config value in-between tests
1 parent ca5f9dd commit ee43b00

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

lib/ecto/adapters/sqlite3.ex

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,17 @@ defmodule Ecto.Adapters.SQLite3 do
227227
end
228228
end
229229

230+
@impl Ecto.Adapter.Schema
231+
def autogenerate(:id), do: nil
232+
def autogenerate(:embed_id), do: Ecto.UUID.generate()
233+
234+
def autogenerate(:binary_id) do
235+
case Application.get_env(:ecto_sqlite3, :binary_id_type, :string) do
236+
:string -> Ecto.UUID.generate()
237+
:binary -> Ecto.UUID.bingenerate()
238+
end
239+
end
240+
230241
##
231242
## Loaders
232243
##

test/ecto/adapters/sqlite3_test.exs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,15 @@ defmodule Ecto.Adapters.SQLite3Test do
33

44
alias Ecto.Adapters.SQLite3
55

6+
@uuid_regex ~R/^[[:xdigit:]]{8}\b-[[:xdigit:]]{4}\b-[[:xdigit:]]{4}\b-[[:xdigit:]]{4}\b-[[:xdigit:]]{12}$/
7+
8+
setup do
9+
original_binary_id_type = Application.get_env(:ecto_sqlite3, :binary_id_type)
10+
on_exit(fn ->
11+
Application.put_env(:ecto_sqlite3, :binary_id_type, original_binary_id_type)
12+
end)
13+
end
14+
615
describe ".storage_up/1" do
716
test "create database" do
817
opts = [database: Temp.path!()]
@@ -51,4 +60,27 @@ defmodule Ecto.Adapters.SQLite3Test do
5160
File.rm(opts[:database])
5261
end
5362
end
63+
64+
describe ".autogenerate/1" do
65+
test ":id must be generated from storage" do
66+
assert SQLite3.autogenerate(:id) == nil
67+
end
68+
69+
test ":embed_id is a UUID in string form" do
70+
assert string_uuid?(SQLite3.autogenerate(:embed_id))
71+
end
72+
73+
test ":binary_id with type :string is a UUID in string form" do
74+
Application.put_env(:ecto_sqlite3, :binary_id_type, :string)
75+
assert string_uuid?(SQLite3.autogenerate(:binary_id))
76+
end
77+
78+
test ":binary_id with type :binary is a UUID in binary form" do
79+
Application.put_env(:ecto_sqlite3, :binary_id_type, :binary)
80+
assert binary_uuid?(SQLite3.autogenerate(:binary_id))
81+
end
82+
end
83+
84+
defp string_uuid?(uuid), do: Regex.match?(@uuid_regex, uuid)
85+
defp binary_uuid?(uuid), do: bit_size(uuid) == 128
5486
end

0 commit comments

Comments
 (0)