Skip to content

Commit

Permalink
improve tables support (#276)
Browse files Browse the repository at this point in the history
* support more table types in the constructor
* add fromtable() and Tables.materializer()
* only run doctests on a single Julia version

---------

Co-authored-by: Pietro Vertechi <pietro.vertechi@protonmail.com>
  • Loading branch information
aplavin and piever authored Feb 23, 2024
1 parent f6b194b commit 7522dfd
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
8 changes: 8 additions & 0 deletions src/tables.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@ function _schema(::Type{T}) where {T<:NTuple{N, Any}} where N
return Tables.Schema{ntuple(identity, N), T}
end

StructArray(cols::Tables.AbstractColumns) = StructArray(Tables.columntable(cols))
StructArray{T}(cols::Tables.AbstractColumns) where {T} = StructArray{T}(Tables.columntable(cols))

# convert from any Tables-compliant object
fromtable(cols) = StructArray(Tables.columntable(cols))
Tables.materializer(::Type{<:StructArray}) = fromtable
Tables.materializer(::StructArray) = fromtable # Tables documentation says it's not needed, but actually it is

function try_compatible_columns(rows::R, s::StructArray) where {R}
Tables.isrowtable(rows) && Tables.columnaccess(rows) || return nothing
T = eltype(rows)
Expand Down
18 changes: 17 additions & 1 deletion test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ using SparseArrays
using InfiniteArrays

using Documenter: doctest
if Base.VERSION >= v"1.6" && Int === Int64
if Base.VERSION == v"1.6" && Int === Int64
doctest(StructArrays)
end

Expand Down Expand Up @@ -717,6 +717,22 @@ end
# Testing integer column "names":
@test invoke(append!, Tuple{StructVector,Any}, StructArray(([0],)), StructArray(([1],))) ==
StructArray(([0, 1],))

dtab = (a=[1,2],) |> Tables.dictcolumntable
@test StructArray(dtab) == [(a=1,), (a=2,)]
@test StructArray{NamedTuple{(:a,), Tuple{Float64}}}(dtab) == [(a=1.,), (a=2.,)]
@test StructVector{NamedTuple{(:a,), Tuple{Float64}}}(dtab) == [(a=1,), (a=2,)]

tblbase = (a=[1,2], b=["3", "4"])
@testset for tblfunc in [Tables.columntable, Tables.rowtable, Tables.dictcolumntable, Tables.dictrowtable]
tbl = tblfunc(tblbase)
sa = StructArrays.fromtable(tbl)
@test sa::StructArray == [(a=1, b="3"), (a=2, b="4")]
sa = Tables.materializer(StructArray)(tbl)
@test sa::StructArray == [(a=1, b="3"), (a=2, b="4")]
sa = Tables.materializer(sa)(tbl)
@test sa::StructArray == [(a=1, b="3"), (a=2, b="4")]
end
end

struct S
Expand Down

0 comments on commit 7522dfd

Please sign in to comment.