Need to run the query and get the result back as JSON format

ecto
#1

How to run the random query and get the result in JSON format and send it as a response. The query will be in the following form
DB Name- POSTGRES
1- select COLUMNLIST from TABLENAME where FILTERS.

No validation required. I do not want to use multiple structs because the query is dynamic in nature and will change at RUNTIME and column list and table name all will change at runtime.

#2

Ecto schema-less queries allow you to supply the table name as a string, interpolate simple where conditions from a keyword list, and select the result into a map with keys from a list.

The ecto ebook has a chapter on schemaless queries: http://pages.plataformatec.com.br/ebook-whats-new-in-ecto-2-0

1 Like
#3

It’s also super easy to manipulate the Postgrex return types if you want to drop down below ecto:

  def result_to_maps(%Postgrex.Result{columns: _, rows: nil}), do: []

  def result_to_maps(%Postgrex.Result{columns: col_nms, rows: rows}) do
    Enum.map(rows, fn(row) -> row_to_map(col_nms, row) end)
  end

  def row_to_map(col_nms, vals) do
    Stream.zip(col_nms, vals)
    |> Enum.into(Map.new(), &(&1))
  end
1 Like