Permalink
Browse files

New, revised query API

  • Loading branch information...
1 parent 3c2b6bc commit ab08ac65b501d74ae47668fcf880d049f03815f3 @yrashk committed Jul 8, 2012
Showing with 45 additions and 14 deletions.
  1. +28 −11 lib/exql.ex
  2. +17 −3 lib/queries/select.ex
View
39 lib/exql.ex
@@ -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
View
20 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, " ")

0 comments on commit ab08ac6

Please sign in to comment.