Current section
Files
Jump to
Current section
Files
lib/mix/tasks/populate.ex
defmodule Mix.Tasks.Populate do
use Mix.Task
alias Subaru.Utils
@shortdoc "Insert mock data"
def run(_args) do
# Ensure the app and its dependencies (like mnesia) are started
Mix.Task.run("app.start")
store = Subaru.store()
db_opts = Application.get_env(:subaru, :db_options, [])
store.init(db_opts)
IO.puts("Populating database with mock data...")
batch =
Enum.reduce(1..100, [], fn _, acc ->
chat_with_users(acc)
end)
:ok = Subaru.commit(batch)
IO.puts("Done.")
end
# This is a dummy schema for the populate task.
# A real app would have these defined in its own schema module.
defmodule Chat do
defstruct [:id, :platform]
end
defmodule User do
defstruct [:id, :name]
end
def chat_with_users(batch) do
num_users = Utils.randint(1, 20)
chat_id = Subaru.gen_id()
user_ids =
Enum.map(1..num_users, fn i ->
%{id: Subaru.gen_id(), name: "user_#{i}"}
end)
user_inserts = Enum.map(user_ids, &{:insert, %User{id: &1.id, name: &1.name}})
links =
Enum.map(user_ids, fn user ->
{:link, :user_in_chat, user.id, chat_id, %{}}
end)
[
{:insert, %Chat{id: chat_id, platform: :telegram}}
| user_inserts ++ links ++ batch
]
end
end