Skip to content

Commit 5e36900

Browse files
authored
Use transaction for multiple updates, multiple queries (#9263)
1 parent db30328 commit 5e36900

File tree

1 file changed

+36
-27
lines changed

1 file changed

+36
-27
lines changed

frameworks/Elixir/phoenix/lib/hello_web/controllers/page_controller.ex

Lines changed: 36 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
defmodule HelloWeb.PageController do
2-
32
use HelloWeb, :controller
43

54
alias Hello.Models.Fortune
@@ -25,13 +24,18 @@ defmodule HelloWeb.PageController do
2524
end
2625

2726
def queries(conn, params) do
28-
:rand.seed(:exsp)
27+
{:ok, worlds} =
28+
Repo.transaction(fn ->
29+
:rand.seed(:exsp)
2930

30-
worlds =
31-
Stream.repeatedly(&random_id/0)
32-
|> Stream.uniq()
33-
|> Stream.map(&Repo.get(World, &1))
34-
|> Enum.take(size(params["queries"]))
31+
worlds =
32+
Stream.repeatedly(&random_id/0)
33+
|> Stream.uniq()
34+
|> Stream.map(&Repo.get(World, &1))
35+
|> Enum.take(size(params["queries"]))
36+
37+
worlds
38+
end)
3539

3640
json(conn, worlds)
3741
end
@@ -50,26 +54,31 @@ defmodule HelloWeb.PageController do
5054
end
5155

5256
def updates(conn, params) do
53-
:rand.seed(:exsp)
54-
55-
worlds =
56-
Stream.repeatedly(&random_id/0)
57-
|> Stream.uniq()
58-
|> Stream.map(&Repo.get(World, &1))
59-
|> Stream.map(fn world -> %{id: world.id, randomnumber: :rand.uniform(@random_max)} end)
60-
|> Enum.take(size(params["queries"]))
61-
# If this is not sorted it sometimes generates
62-
# FAIL for http://tfb-server:8080/updates/20
63-
# Only 20470 executed queries in the database out of roughly 20480 expected.
64-
|> Enum.sort_by(& &1.id)
65-
66-
Repo.insert_all(
67-
World,
68-
worlds,
69-
on_conflict: {:replace_all_except, [:id]},
70-
conflict_target: [:id],
71-
returning: false
72-
)
57+
{:ok, worlds} =
58+
Repo.transaction(fn ->
59+
:rand.seed(:exsp)
60+
61+
worlds =
62+
Stream.repeatedly(&random_id/0)
63+
|> Stream.uniq()
64+
|> Stream.map(&Repo.get(World, &1))
65+
|> Stream.map(fn world -> %{id: world.id, randomnumber: :rand.uniform(@random_max)} end)
66+
|> Enum.take(size(params["queries"]))
67+
# If this is not sorted it sometimes generates
68+
# FAIL for http://tfb-server:8080/updates/20
69+
# Only 20470 executed queries in the database out of roughly 20480 expected.
70+
|> Enum.sort_by(& &1.id)
71+
72+
Repo.insert_all(
73+
World,
74+
worlds,
75+
on_conflict: {:replace_all_except, [:id]},
76+
conflict_target: [:id],
77+
returning: false
78+
)
79+
80+
worlds
81+
end)
7382

7483
json(conn, worlds)
7584
end

0 commit comments

Comments
 (0)