Skip to content

Commit

Permalink
chore: try reloading single record on insert with auto increment prim…
Browse files Browse the repository at this point in the history
…ary key
  • Loading branch information
lejoko committed May 16, 2024
1 parent ab5baac commit b70b563
Showing 1 changed file with 17 additions and 11 deletions.
28 changes: 17 additions & 11 deletions lib/data_layer.ex
Original file line number Diff line number Diff line change
Expand Up @@ -699,17 +699,15 @@ defmodule AshMysql.DataLayer do
opts
end

ecto_changesets = Enum.map(changesets, & &1.attributes)

opts =
if schema = Enum.at(changesets, 0).context[:data_layer][:schema] do
Keyword.put(opts, :prefix, schema)
else
opts
end

ecto_changesets = Enum.map(changesets, & &1.attributes)
resource_for_returning = if options.return_records?, do: resource, else: nil

result = insert_all_returning(source, ecto_changesets, repo, resource_for_returning, opts)

case result do
Expand Down Expand Up @@ -750,18 +748,26 @@ defmodule AshMysql.DataLayer do
defp insert_all_returning(source, entries, repo, resource, opts) do
{count, nil} = repo.insert_all(source, entries, opts)
reload_key = Ash.Resource.Info.primary_key(resource) |> Enum.at(0)
keys_to_reload = entries |> Enum.map(&Map.get(&1, reload_key))
keys_to_reload = entries |> Enum.map(&Map.get(&1, reload_key)) |> Enum.filter(&(!is_nil(&1)))

result =
case keys_to_reload do
[] ->
Ecto.Query.from(s in source, where: field(s, ^reload_key) == fragment("LAST_INSERT_ID()"))
|> repo.all()

unordered =
Ecto.Query.from(s in source, where: field(s, ^reload_key) in ^keys_to_reload) |> repo.all()
_ ->
unordered =
Ecto.Query.from(s in source, where: field(s, ^reload_key) in ^keys_to_reload)
|> repo.all()

indexed = unordered |> Enum.group_by(&Map.get(&1, reload_key))
indexed = unordered |> Enum.group_by(&Map.get(&1, reload_key))

ordered =
keys_to_reload
|> Enum.map(&(Map.get(indexed, &1) |> Enum.at(0)))
keys_to_reload
|> Enum.map(&(Map.get(indexed, &1) |> Enum.at(0)))
end

{count, ordered}
{count, result}
end

defp upsert_set(resource, changesets, options) do
Expand Down

0 comments on commit b70b563

Please sign in to comment.