Skip to content

Instantly share code, notes, and snippets.

@Wigny
Last active February 5, 2025 13:42
Show Gist options
  • Save Wigny/1ce5d21142ccd02c546ee626a0185096 to your computer and use it in GitHub Desktop.
Save Wigny/1ce5d21142ccd02c546ee626a0185096 to your computer and use it in GitHub Desktop.
MySQL Ecto returning
defmodule MySQL do
defmacro __using__(_opts \\ []) do
quote do
defoverridable insert_all: 3
def insert_all(schema_or_source, entries, opts) when is_list(entries) do
{returning, opts} = Keyword.pop(opts, :returning)
if returning do
import Ecto.Query
{:ok, return} =
transaction(fn ->
super(schema_or_source, entries, opts)
inserts =
all(
from p in schema_or_source,
where: p.id >= fragment("LAST_INSERT_ID()"),
where: p.id <= fragment("LAST_INSERT_ID()") + (fragment("ROW_COUNT()") - 1)
)
{length(inserts), inserts}
end)
return
else
super(schema_or_source, entries, opts)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment