 defmodule Sqlite.Ecto.Query do
   import Sqlite.Ecto.Transaction, only: [with_savepoint: 2]
-  import Sqlite.Ecto.Util, only: [exec: 2, random_id: 0, quote_id: 1]
+  import Sqlite.Ecto.Util, only: [assemble: 1, exec: 2, random_id: 0, quote_id: 1]
 
   def query(pid, sql=<<"ALTER TABLE ", _::binary>>, _params, _opts) do
     alter_table_query(pid, sql)


  # XXX How do we handle inserting datetime values?
  def insert(table, [], returning) do
    rets = returning_clause(table, returning, "INSERT")
    "INSERT INTO #{quote_id(table)} DEFAULT VALUES" <> rets
  end
  def insert(table, fields, returning) do
    cols = Enum.map_join(fields, ",", &quote_id/1)
    vals = 1..length(fields) |> Enum.map_join(",", &"?#{&1}")
    rets = returning_clause(table, returning, "INSERT")
    "INSERT INTO #{quote_id(table)} (#{cols}) VALUES (#{vals})" <> rets
  end

  def update(table, fields, filters, returning) do
    {vals, count} = Enum.map_reduce(fields, 1, fn (i, acc) ->
      {"#{quote_id(i)} = ?#{acc}", acc + 1}
    end)
    where = where_filter(filters, count)
    rets = returning_clause(table, returning, "UPDATE")
    "UPDATE #{quote_id(table)} SET " <> Enum.join(vals, ", ") <> where <> rets
  end

  def delete(table, filters, returning) do
    where = where_filter(filters)
    return = returning_clause(table, returning, "DELETE")
    "DELETE FROM " <> quote_id(table) <> where <> return
  end

  ## Helpers

    |> Enum.map_reduce(start, fn (i, acc) -> {"#{i} = ?#{acc}", acc + 1} end)
    |> (fn ({filters, _acc}) -> filters end).()
    |> Enum.join(" AND ")
    |> (fn (clause) -> "WHERE " <> clause end).()
  end
end
