/
queryable.ex
44 lines (38 loc) · 1.04 KB
/
queryable.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
defprotocol Ecto.Queryable do
@moduledoc """
Converts a data structure into an `Ecto.Query`.
"""
@doc """
Converts the given `data` into an `Ecto.Query`.
"""
def to_query(data)
end
defimpl Ecto.Queryable, for: Ecto.Query do
def to_query(query), do: query
end
defimpl Ecto.Queryable, for: BitString do
def to_query(source) when is_binary(source),
do: %Ecto.Query{from: {source, nil}}
end
defimpl Ecto.Queryable, for: Atom do
def to_query(module) do
try do
%Ecto.Query{from: {module.__schema__(:source), module}}
rescue
UndefinedFunctionError ->
message = if :code.is_loaded(module) do
"the given module is not queryable"
else
"the given module does not exist"
end
raise Protocol.UndefinedError,
protocol: @protocol,
value: module,
description: message
end
end
end
defimpl Ecto.Queryable, for: Tuple do
def to_query(from = {source, model}) when is_binary(source) and is_atom(model),
do: %Ecto.Query{from: from}
end