Skip to content

Instantly share code, notes, and snippets.

@fuelen
Last active July 28, 2021 13:48
Show Gist options
  • Save fuelen/61b0268df513d844a4197a3038c35a57 to your computer and use it in GitHub Desktop.
Save fuelen/61b0268df513d844a4197a3038c35a57 to your computer and use it in GitHub Desktop.
How to remove array from array using ecto
defmodule MyProject.Macro do
@doc """
@doc """
## Examples:
iex> query |> update([t], set: [unread_message_ids: array_substract(t.unread_message_ids, ^message_ids)])
"""
defmacro array_substract(first, second) do
quote do
fragment(
"""
COALESCE((
SELECT array_agg(elem)
FROM unnest(?) elem
WHERE elem <> all(?)), ?
)
""",
unquote(first),
type(unquote(second), unquote(first)),
type(unquote(second), [])
)
end
end
end
@andreyuhai
Copy link

This query just didn't work for me somehow so I've created the same function with another query which I think looks better.
https://gist.github.com/andreyuhai/cdff6e6b8791d6c8f510c8b15fcfd4c9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment