@@ -227,18 +227,45 @@ function mtg_table(mtg::Node, vars=nothing)
227227 ColumnTable (names_, cols_)
228228end
229229
230+ @inline function _materialize_table (source, sink)
231+ sink === nothing && return source
232+
233+ # Preferred path for Tables-compatible sinks (e.g. DataFrame type/instance).
234+ materializer = try
235+ Tables. materializer (sink)
236+ catch
237+ try
238+ Tables. materializer (typeof (sink))
239+ catch
240+ nothing
241+ end
242+ end
243+ materializer != = nothing && return materializer (source)
244+
245+ # Generic fallback for callable sinks, e.g. sink = x -> MyType(x)
246+ applicable (sink, source) && return sink (source)
247+
248+ error (
249+ " Unsupported sink $(sink) . " ,
250+ " Provide a Tables.jl sink (type or instance, e.g. DataFrame) or a callable that accepts a table."
251+ )
252+ end
253+
230254"""
231- to_table(mtg::Node; symbol=nothing, vars=nothing)
255+ to_table(mtg::Node; symbol=nothing, vars=nothing, sink=nothing)
256+
257+ Generic table conversion entry-point.
232258
233- Convenience helper to get a Tables.jl-compatible view from an MTG.
234- - `symbol=nothing`: unified traversal-ordered table (`mtg_table`)
235- - `symbol=<symbol>`: per-symbol table (`symbol_table`)
259+ - `symbol=nothing`: unified traversal-ordered table
260+ - `symbol=<symbol>`: per-symbol table
236261- `vars`: optional attribute selection (`Symbol`/`String`/vector/tuple)
262+ - `sink`: optional sink materialization (e.g. `sink=DataFrame` if `DataFrames.jl` is loaded)
237263"""
238- function to_table (mtg:: Node ; symbol= nothing , vars= nothing )
239- symbol === nothing ? mtg_table (mtg, vars) : symbol_table (mtg, symbol, vars)
264+ function to_table (mtg:: Node ; symbol= nothing , vars= nothing , sink= nothing )
265+ source = symbol === nothing ? mtg_table (mtg, vars) : symbol_table (mtg, symbol, vars)
266+ _materialize_table (source, sink)
240267end
241268
242269Tables. istable (:: Type{<:Node} ) = true
243270Tables. columnaccess (:: Type{<:Node} ) = true
244- Tables. columns (mtg:: Node ) = mtg_table (mtg)
271+ Tables. columns (mtg:: Node ) = to_table (mtg)
0 commit comments