Last active
November 1, 2016 18:30
-
-
Save jerel/7059c3cdefccdf5d6f51b85ca631b95b to your computer and use it in GitHub Desktop.
In Elixir soft delete records immediately followed by a real delete a day later. (untested example)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule User do | |
def all do | |
from(u in UserSchema, where: is_nil(u.deleted_at)) |> Repo.all | |
end | |
def delete(user_id) do | |
user = Repo.get!(UserSchema, user_id) | |
changeset = Ecto.Changeset.change(user, deleted_at: Ecto.DateTime.utc) | |
Repo.update(changeset) | |
end | |
end | |
defmodule Garbage do | |
use GenServer | |
def start_link() do | |
GenServer.start_link(__MODULE__, [], name: __MODULE__) | |
end | |
def init(_) do | |
Process.send_after(self, :user_clean, 1000 * 60 * 60 * 24) | |
{:ok, []} | |
end | |
def handle_info(:user_clean, state) do | |
day_ago = Timex.shift(DateTime.utc_now, days: -1) | |
from(u in UserSchema, where: not(is_nil(u.deleted_at)) and u.deleted_at < day_ago) |> Repo.delete_all | |
{:noreply, state} | |
end | |
end | |
// start the garbage collector in the application | |
children = [ | |
worker(MyApp.Garbage, []), | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment