Skip to content

Commit 9f4d34d

Browse files
committed
Add support for custom/composite PKs on DB.reload/1
1 parent b22d94b commit 9f4d34d

2 files changed

Lines changed: 36 additions & 4 deletions

File tree

lib/feeb/db.ex

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -237,11 +237,8 @@ defmodule Feeb.DB do
237237
end
238238

239239
def reload(%schema{} = struct) do
240-
# Support for custom or composite PKs is TODO
241-
primary_key_cols = [:id]
242-
243240
bindings =
244-
Enum.map(primary_key_cols, fn col_name ->
241+
Enum.map(schema.__primary_keys__() || [], fn col_name ->
245242
Map.fetch!(struct, col_name)
246243
end)
247244

test/db/db_test.exs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -790,6 +790,24 @@ defmodule Feeb.DBTest do
790790
refute reloaded_post.updated_at == post.updated_at
791791
end
792792

793+
test "reloads schemas with composite PKs", %{shard_id: shard_id} do
794+
DB.begin(@context, shard_id, :write)
795+
796+
order_item =
797+
%{order_id: 1, product_id: 2, quantity: 10, price: 50}
798+
|> OrderItems.new()
799+
|> DB.insert!()
800+
801+
# Now we can expect the order item to have a quantity of 20
802+
assert {:ok, _} =
803+
order_item
804+
|> OrderItems.update(%{quantity: 20})
805+
|> DB.update()
806+
807+
assert reloaded_order_item = DB.reload(order_item)
808+
assert reloaded_order_item.quantity == 20
809+
end
810+
793811
test "returns nil when the requested schema is not found", %{shard_id: shard_id} do
794812
DB.begin(@context, shard_id, :write)
795813

@@ -857,6 +875,23 @@ defmodule Feeb.DBTest do
857875
# Order is kept
858876
assert [nil, %{id: 1}] = DB.reload([post_2, post_1])
859877
end
878+
879+
test "raises if the requested schema has no PKs", %{shard_id: shard_id} do
880+
DB.begin(@context, shard_id, :write)
881+
882+
all_types =
883+
AllTypes.creation_params()
884+
|> AllTypes.new()
885+
|> DB.insert!()
886+
887+
%{message: error} =
888+
assert_raise RuntimeError, fn ->
889+
DB.reload(all_types)
890+
end
891+
892+
assert error =~ "Can't generate adhoc query"
893+
assert error =~ "because Sample.AllTypes has no PKs"
894+
end
860895
end
861896

862897
describe "reload!/1" do

0 commit comments

Comments
 (0)