From 86675725ffecbde71a860fc2ed0162ac1e591707 Mon Sep 17 00:00:00 2001 From: Daniel Kempkens Date: Wed, 16 Aug 2023 13:22:57 +0200 Subject: [PATCH] fix: Use left_joins in some places --- lib/bdfr_browser/chat.ex | 2 +- lib/bdfr_browser/importer.ex | 12 +++++++----- lib/bdfr_browser/post.ex | 4 ++-- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/lib/bdfr_browser/chat.ex b/lib/bdfr_browser/chat.ex index 031c920..c6106a7 100644 --- a/lib/bdfr_browser/chat.ex +++ b/lib/bdfr_browser/chat.ex @@ -15,7 +15,7 @@ defmodule BdfrBrowser.Chat do def listing do from(c in __MODULE__, - join: m in assoc(c, :messages), + left_join: m in assoc(c, :messages), select: %{id: c.id, accounts: c.accounts, num_messages: count(m.id), latest_message: max(m.posted_at)}, order_by: [desc: max(m.posted_at)], group_by: c.id diff --git a/lib/bdfr_browser/importer.ex b/lib/bdfr_browser/importer.ex index 2fe452e..0f29ef1 100644 --- a/lib/bdfr_browser/importer.ex +++ b/lib/bdfr_browser/importer.ex @@ -25,11 +25,13 @@ defmodule BdfrBrowser.Importer do folders = list_folders(sort: :asc) for folder <- folders do - %Subreddit{name: folder} - |> Repo.insert( - on_conflict: :nothing, - conflict_target: :name - ) + subreddit = Repo.get_by(Subreddit, name: folder) + + if is_nil(subreddit) do + Repo.insert(%Subreddit{name: folder}) + else + subreddit + end end end diff --git a/lib/bdfr_browser/post.ex b/lib/bdfr_browser/post.ex index bb8d712..6ccc1e1 100644 --- a/lib/bdfr_browser/post.ex +++ b/lib/bdfr_browser/post.ex @@ -37,7 +37,7 @@ defmodule BdfrBrowser.Post do def during_range(subreddit, start_date, end_date) do from(p in __MODULE__, - join: c in assoc(p, :comments), + left_join: c in assoc(p, :comments), select: %{id: p.id, title: p.title, author: p.author, posted_at: p.posted_at, num_comments: count(c.id)}, where: p.subreddit_id == ^subreddit.id and type(p.posted_at, :date) >= ^start_date and @@ -63,7 +63,7 @@ defmodule BdfrBrowser.Post do def by_author(author) do from(p in __MODULE__, - join: c in assoc(p, :comments), + left_join: c in assoc(p, :comments), join: s in assoc(p, :subreddit), select: %{ id: p.id,