Skip to content

Commit

Permalink
Merge pull request #13 from dwyl/get_by
Browse files Browse the repository at this point in the history
Get by
  • Loading branch information
nelsonic authored Oct 31, 2018
2 parents b3d20ca + 66f3ec3 commit 4cbf9d7
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
21 changes: 19 additions & 2 deletions lib/alog.ex
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ defmodule Alog do

defmacro __before_compile__(_env) do
quote generated: true, location: :keep do
import Ecto.Query, only: [from: 2, subquery: 1]
import Ecto.Query
import Ecto.Query.API, only: [field: 2]

@repo __MODULE__ |> Module.split() |> List.first() |> Module.concat("Repo")

Expand Down Expand Up @@ -119,9 +120,25 @@ defmodule Alog do

@doc """
Gets an item from the database that matches the given clause.
User.get_by(username: "admin")
User.get_by(first_name: "Charlie", age: 27)
"""
def get_by(clauses) do
@repo.get_by(__MODULE__, clauses)
sub =
__MODULE__
|> (fn q ->
Enum.reduce(clauses, q, fn {key, value}, q ->
q |> where([m], field(m, ^key) == ^value)
end)
end).()
|> order_by([m], desc: m.inserted_at)
|> limit([m], 1)
|> select([m], m)

query = from(m in subquery(sub), where: not m.deleted, select: m)

item = @repo.one(query)
end

@doc """
Expand Down
16 changes: 16 additions & 0 deletions test/alog_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,22 @@ defmodule AlogTest do
end
end

describe "get_by/2:" do
test "only returns one result" do
{:ok, user} = User.insert(%{name: "Thor", username: "gdofthndr12", postcode: "E2 0SY"})
{:ok, user_2} = User.insert(%{name: "Loki", username: "mschfmkr", postcode: "E2 0SY"})

assert User.get_by(postcode: "E2 0SY") == user_2
end

test "works with multiple clauses" do
{:ok, user} = User.insert(%{name: "Thor", username: "gdofthndr12", postcode: "E2 0SY"})
{:ok, user_2} = User.insert(%{name: "Loki", username: "mschfmkr", postcode: "E2 0SY"})

assert User.get_by(postcode: "E2 0SY", name: "Thor") == user
end
end

describe "required fields" do
test "schema without delete field raises error" do
assert_raise RuntimeError, fn ->
Expand Down

0 comments on commit 4cbf9d7

Please sign in to comment.