Search code examples
elixirecto

ruby Sequel query ecto elixir


I have this expression written in ruby

vendors = vendors.where(%("known_macs" @> ARRAY[?]), params[:mac].upcase[0, 8])

I want to write this in ecto.. my whole structure is as

  def index(conn, params) do
    known_macs =
      params["mac"]
      |> upcase

    vendors =
      from(v in Vendor)
      |> with_exid_if_given(params["id"])
      |> with_name_if_given(params["name"])
      |> with_known_macs_if_given(known_macs)
      |> preload(:vendor_models)
      |> Repo.all

    conn
    |> render(VendorView, "index.json", %{vendors: vendors})
  end

  defp with_exid_if_given(query, nil), do: query
  defp with_exid_if_given(query, exid) do
    query
    |> where([v], v.exid == ^exid)
  end

  defp with_name_if_given(query, nil), do: query
  defp with_name_if_given(query, name) do
    query
    |> where([v], like(v.name, ^name))
  end

  defp with_known_macs_if_given(query, nil), do: query
  defp with_known_macs_if_given(query, known_macs) do
    query
    |> where([v], %("known_macs" @> ARRAY[?]), known_macs)
  end

I have no idea how to check mac address in query. when I pass a mac address then in ruby query it looks like #<Sequel::Postgres::Dataset: "SELECT * FROM \"vendors\" WHERE (\"known_macs\" @> ARRAY['8C:11:CB'])">


Solution

  • this could be done like this

      defp with_known_macs_if_given(query, nil), do: query
      defp with_known_macs_if_given(query, known_macs) do
        query
        |> where([v], fragment("? @> ARRAY[?]", v.known_macs, ^known_macs))
      end