Skip to content

Commit

Permalink
New, revised query API
Browse files Browse the repository at this point in the history
  • Loading branch information
yrashk committed Jul 8, 2012
1 parent 3c2b6bc commit ab08ac6
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 14 deletions.
39 changes: 28 additions & 11 deletions lib/exql.ex
Expand Up @@ -5,17 +5,34 @@ defmodule ExQL do
end
end

defdelegate [select: 0], to: ExQL.Select, as: :new

defmacro expr(c) do
quote do
f = fn() ->
import Elixir.Builtin, except: unquote(ExQL.Condition.__ops__)
import ExQL.Condition, only: unquote(ExQL.Condition.__ops__)
unquote(c)
end
f.()
end
defmacro select(block // [do: nil]) do
query = ExQL.Select.new
case block[:do] do
{:__block__, _, body} -> :ok
nil -> body = []
expr -> body = [expr]
end
body =
List.reverse(Enum.reduce body, [],
fn(expr, acc) ->
case acc do
[i] -> [{:/>, 0, [i, expr]}]
_ -> [expr|acc]
end
end)
case body do
[] -> quote do: unquote(query)
[expr] ->
quote do
import ExQL.Select
unquote(query) /> unquote(expr)
end
[l,r] ->
quote do
import ExQL.Select
unquote(query) /> (unquote(l) /> unquote(r))
end
end
end

end
20 changes: 17 additions & 3 deletions lib/queries/select.ex
@@ -1,9 +1,23 @@
defrecord ExQL.Select, dict: [fields: :*] do
use ExQL.Query

def fields(v, query), do: query.dict Keyword.put(query.dict, :fields, v)
def from(v, query), do: query.dict Keyword.put(query.dict, :from, v)
def where(v, query), do: query.dict Keyword.put(query.dict, :where, v)
def fields(query, v), do: query.dict Keyword.put(query.dict, :fields, v)
def from(query, v), do: query.dict Keyword.put(query.dict, :from, v)

defmacro where(query, block) when is_tuple(block) do
quote do
f = fn() ->
import Elixir.Builtin, except: unquote(ExQL.Condition.__ops__)
import ExQL.Condition, only: unquote(ExQL.Condition.__ops__)
unquote(block)
end
ExQL.Select._where(unquote(query), f.())
end
end
defmacro where(query, value) do
quote do: ExQL.Select._where(unquote(query), unquote(value))
end
def _where(query, v), do: query.dict Keyword.put(query.dict, :where, v)

def statement(:modifiers, query) do
ExQL.Expression.join(dict(query)[:modifiers], :raw, " ")
Expand Down

0 comments on commit ab08ac6

Please sign in to comment.