Skip to content

Commit

Permalink
Handle ETS tables with mixed number of columns (#21)
Browse files Browse the repository at this point in the history
* Handle ETS tables with mixed number of columns

* Update lib/kino/ets.ex

Co-authored-by: José Valim <[email protected]>

Co-authored-by: José Valim <[email protected]>
  • Loading branch information
jonatanklosko and josevalim authored Jun 21, 2021
1 parent f8cacc2 commit ed0ae42
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
18 changes: 10 additions & 8 deletions lib/kino/ets.ex
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ defmodule Kino.ETS do

columns =
case :ets.match_object(state.tid, :_, 1) do
{[record], _} -> columns_structure_from_record(record)
{[record], _} -> columns_structure_for_records([record])
:"$end_of_table" -> []
end

Expand All @@ -94,7 +94,7 @@ defmodule Kino.ETS do
columns =
case records do
[] -> :initial
[record | _] -> columns_structure_from_record(record)
records -> columns_structure_for_records(records)
end

send(pid, {:rows, %{rows: rows, total_rows: total_rows, columns: columns}})
Expand All @@ -106,13 +106,15 @@ defmodule Kino.ETS do
{:stop, :shutdown, state}
end

defp columns_structure_from_record(record) do
record
|> Tuple.to_list()
|> Enum.with_index()
|> Enum.map(fn {_, idx} ->
defp columns_structure_for_records(records) do
max_columns =
records
|> Enum.map(&tuple_size/1)
|> Enum.max()

for idx <- 0..(max_columns - 1) do
%{key: idx, label: "#{idx + 1}"}
end)
end
end

defp get_records(tid, rows_spec) do
Expand Down
23 changes: 23 additions & 0 deletions test/kino/ets_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,29 @@ defmodule Kino.ETSTest do
columns: [_, _]
}}
end

test "determines enough columns to accommodate longest record", %{tid: tid} do
:ets.insert(tid, {4, "Sherlock Holmes", 100})
:ets.insert(tid, {5, "John Watson", 150, :doctor})
:ets.insert(tid, {6})

widget = Kino.ETS.start(tid)
connect_self(widget)

spec = %{
offset: 0,
limit: 10,
order_by: 0,
order: :asc
}

send(widget.pid, {:get_rows, self(), spec})

assert_receive {:rows,
%{
columns: [_, _, _, _]
}}
end
end

defp connect_self(widget) do
Expand Down

0 comments on commit ed0ae42

Please sign in to comment.