Skip to content

Commit

Permalink
Merge 76e5463 into 2cee517
Browse files Browse the repository at this point in the history
  • Loading branch information
Atlas42 committed Dec 5, 2019
2 parents 2cee517 + 76e5463 commit 5185854
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
9 changes: 7 additions & 2 deletions lib/nebulex_ecto/repo.ex
Expand Up @@ -173,7 +173,7 @@ defmodule NebulexEcto.Repo do

case fun.(struct_or_changeset, opts) do
{:ok, schema} = res ->
cache_key = nbx_key || key(schema, schema.id)
cache_key = nbx_key || key(schema, primary_key(schema))
_ = cache_evict(nbx_evict, cache_key, schema)
res

Expand All @@ -187,7 +187,7 @@ defmodule NebulexEcto.Repo do
{nbx_evict, opts} = Keyword.pop(opts, :nbx_evict, :delete)

schema = fun.(struct_or_changeset, opts)
cache_key = nbx_key || key(schema, schema.id)
cache_key = nbx_key || key(schema, primary_key(schema))
_ = cache_evict(nbx_evict, cache_key, schema)
schema
end
Expand All @@ -197,6 +197,11 @@ defmodule NebulexEcto.Repo do

defp cache_evict(:replace, key, value),
do: @cache.set(key, value)

defp primary_key(schema) do
[key] = schema.__struct__.__schema__(:primary_key)
Map.get(schema, key)
end
end
end

Expand Down
33 changes: 33 additions & 0 deletions test/nebulex_ecto/repo_test.exs
Expand Up @@ -20,6 +20,16 @@ defmodule NebulexEcto.RepoTest do
end
end

defmodule MyAltSchema do
use Ecto.Schema

@primary_key {:uid, :id, []}

schema "my_alt_schema" do
field(:x, :string)
end
end

setup do
{:ok, pid} = Cache.start_link(n_generations: 2)
:ok
Expand Down Expand Up @@ -69,6 +79,29 @@ defmodule NebulexEcto.RepoTest do
assert CacheableRepo.get!(MySchema, 1)
end

test "Alt key get and get!" do
schema = %MyAltSchema{uid: 1, x: "abc"}
{:ok, _} = Repo.insert(schema)

# shouldn't be in cache
refute Cache.get({MyAltSchema, 1})

# shouldn't be in cache neither in repo
refute CacheableRepo.get(MyAltSchema, -1)

assert_raise Ecto.NoResultsError, fn ->
CacheableRepo.get!(MyAltSchema, -1)
end

# fetch from repo and put it in cache
assert CacheableRepo.get(MyAltSchema, 1)
assert Cache.get!({MyAltSchema, 1})

# remove from repo and it should be still cached
assert Repo.delete!(schema)
assert CacheableRepo.get!(MyAltSchema, 1)
end

test "get_by and get_by! when queryable is a schema" do
schema = %MySchema{id: 1, x: "abc"}
{:ok, _} = Repo.insert(schema)
Expand Down

0 comments on commit 5185854

Please sign in to comment.