#
# Copyright (c) 2016-2026 Deephaven Data Labs and Patent Pending
#
"""This module provides various ways to make a Deephaven table."""
from collections.abc import Callable, Mapping, Sequence
from functools import wraps
from typing import Any
import jpy
import pandas as pd
from deephaven import DHError, execution_context
from deephaven._wrapper import JObjectWrapper
from deephaven.column import InputColumn
from deephaven.dtypes import DType
from deephaven.execution_context import ExecutionContext
from deephaven.jcompat import j_lambda, j_list_to_list, to_sequence
from deephaven.table import Table, TableDefinition, TableDefinitionLike
from deephaven.time import DurationLike, InstantLike, to_j_duration, to_j_instant
from deephaven.update_graph import auto_locking_ctx
_JTableFactory = jpy.get_type("io.deephaven.engine.table.TableFactory")
_JTableTools = jpy.get_type("io.deephaven.engine.util.TableTools")
_JDynamicTableWriter = jpy.get_type(
"io.deephaven.engine.table.impl.util.DynamicTableWriter"
)
_JAppendOnlyArrayBackedInputTable = jpy.get_type(
"io.deephaven.engine.table.impl.util.AppendOnlyArrayBackedInputTable"
)
_JKeyedArrayBackedInputTable = jpy.get_type(
"io.deephaven.engine.table.impl.util.KeyedArrayBackedInputTable"
)
_JTableDefinition = jpy.get_type("io.deephaven.engine.table.TableDefinition")
_JTable = jpy.get_type("io.deephaven.engine.table.Table")
_J_InputTableUpdater = jpy.get_type("io.deephaven.engine.util.input.InputTableUpdater")
_JRingTableTools = jpy.get_type(
"io.deephaven.engine.table.impl.sources.ring.RingTableTools"
)
_JSupplier = jpy.get_type("java.util.function.Supplier")
_JOptional = jpy.get_type("java.util.Optional")
_JDuration = jpy.get_type("java.time.Duration")
_JFunctionGeneratedTableFactory = jpy.get_type(
"io.deephaven.engine.table.impl.util.FunctionGeneratedTableFactory"
)
_JFunctionGeneratedTableSpec = jpy.get_type(
"io.deephaven.engine.table.impl.util.FunctionGeneratedTableSpec"
)
_JPythonInputTableStatusListenerAdapter = jpy.get_type(
"io.deephaven.integrations.python.PythonInputTableStatusListenerAdapter"
)
def _DEFAULT_INPUT_TABLE_ON_ERROR_CALLBACK(e: Exception) -> None:
print(f"An error occurred during InputTable async operation: {e}")
return
def _error_callback_wrapper(
callback: Callable[[Exception], None],
) -> Callable[[Exception], None]:
@wraps(callback)
def wrapper(e: Exception) -> None:
callback(RuntimeError(e))
return wrapper
[docs]
def empty_table(size: int) -> Table:
"""Creates a table with rows but no columns.
Args:
size (int): the number of rows
Returns:
a Table
Raises:
DHError
"""
try:
return Table(j_table=_JTableTools.emptyTable(size))
except Exception as e:
raise DHError(e, "failed to create an empty table.") from e
[docs]
def time_table(
period: DurationLike,
start_time: InstantLike | None = None,
blink_table: bool = False,
) -> Table:
"""Creates a table that adds a new row on a regular interval.
Args:
period (DurationLike):
time interval between new row additions, can be expressed as an integer in nanoseconds,
a time interval string, e.g. "PT00:00:00.001" or "PT1s", or other time duration types.
start_time (Optional[InstantLike]):
start time for adding new rows, defaults to None which means use the current time
as the start time.
blink_table (bool): if the time table should be a blink table, defaults to False
Returns:
a Table
Raises:
DHError
"""
try:
builder = _JTableTools.timeTableBuilder()
if period is None:
raise ValueError("period must be specified")
builder.period(to_j_duration(period))
# An int start_time of 0 is the Epoch, so test for None rather than for truth.
if start_time is not None:
builder.startTime(to_j_instant(start_time))
if blink_table:
builder.blinkTable(blink_table)
return Table(j_table=builder.build())
except Exception as e:
raise DHError(e, "failed to create a time table.") from e
[docs]
def new_table(cols: Sequence[InputColumn] | Mapping[str, Sequence]) -> Table:
"""Creates an in-memory table from a list of input columns or a Dict (mapping) of column names and column data.
Each column must have an equal number of elements.
When the input is a mapping, an intermediary Pandas DataFrame is created from the mapping, which then is converted
to an in-memory table. In this case, as opposed to when the input is a list of InputColumns, the column types are
determined by Pandas' type inference logic.
Args:
cols (Union[Sequence[InputColumn], Mapping[str, Sequence]]): a list of InputColumns or a mapping of columns
names and column data.
Returns:
a Table
Raises:
DHError
"""
try:
if isinstance(cols, Mapping):
from deephaven.pandas import to_table
df = pd.DataFrame(cols).convert_dtypes()
return to_table(df)
else:
return Table(
j_table=_JTableFactory.newTable(*[col.j_column for col in cols])
)
except Exception as e:
raise DHError(e, "failed to create a new table.") from e
[docs]
def merge(tables: Sequence[Table]) -> Table:
"""Combines two or more tables into one aggregate table. This essentially appends the tables one on top of the
other.
Args:
tables (Sequence[Table]): the source tables
Returns:
a Table
Raises:
DHError
"""
try:
with auto_locking_ctx(*tables):
return Table(j_table=_JTableTools.merge([t.j_table for t in tables]))
except Exception as e:
raise DHError(e, "merge tables operation failed.") from e
[docs]
def merge_sorted(tables: Sequence[Table], order_by: str) -> Table:
"""Combines two or more tables into one sorted, aggregate table. This essentially stacks the tables one on top
of the other and sorts the result. merge_sorted is more efficient than using merge
followed by sort. The input tables must be already sorted on the order_by column.
Args:
tables (Sequence[Table]): the source tables
order_by (str): the name of the key column
Returns:
a Table
Raises:
DHError
"""
try:
with auto_locking_ctx(*tables):
return Table(
j_table=_JTableTools.mergeSorted(order_by, *[t.j_table for t in tables])
)
except Exception as e:
raise DHError(e, "merge sorted operation failed.") from e
[docs]
class DynamicTableWriter(JObjectWrapper):
"""The DynamicTableWriter creates a new in-memory table and supports writing data to it.
This class implements the context manager protocol and thus can be used in with statements.
"""
j_object_type = _JDynamicTableWriter
def __init__(self, col_defs: dict[str, DType]):
"""Initializes the writer and creates a new in-memory table.
Args:
col_defs(dict[str, DTypes]): a map of column names and types of the new table
Raises:
DHError
"""
col_names = list(col_defs.keys())
col_dtypes = list(col_defs.values())
try:
self._j_table_writer = _JDynamicTableWriter(
col_names, [t.qst_type for t in col_dtypes]
)
self.table = Table(j_table=self._j_table_writer.getTable())
except Exception as e:
raise DHError(e, "failed to create a DynamicTableWriter.") from e
@property
def j_object(self) -> jpy.JType:
return self._j_table_writer
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
[docs]
def close(self) -> None:
"""Closes the writer.
Raises:
DHError
"""
try:
self._j_table_writer.close()
except Exception as e:
raise DHError(e, "failed to close the writer.") from e
[docs]
def write_row(self, *values: Any) -> None:
"""Writes a row to the newly created table.
The type of value must be convertible (safely or unsafely, e.g. lose precision, overflow, etc.) to the type
of the corresponding column.
Args:
*values (Any): the values of the new row, the data types of these values must match the column definitions
of the table
Raises:
DHError
"""
try:
values = tuple(to_sequence(values))
self._j_table_writer.logRowPermissive(values)
except Exception as e:
raise DHError(e, "failed to write a row.") from e
[docs]
def ring_table(parent: Table, capacity: int, initialize: bool = True) -> Table:
"""Creates a ring table that retains the latest 'capacity' number of rows from the parent table.
Latest rows are determined solely by the new rows added to the parent table, deleted rows are ignored,
and updated rows are not expected and will raise an exception.
Ring table is mostly used with blink tables which do not retain their own data for more than an update cycle.
Args:
parent (Table): the parent table
capacity (int): the capacity of the ring table
initialize (bool): whether to initialize the ring table with a snapshot of the parent table, default is True
Returns:
a Table
Raises:
DHError
"""
try:
return Table(j_table=_JRingTableTools.of(parent.j_table, capacity, initialize))
except Exception as e:
raise DHError(e, "failed to create a ring table.") from e
[docs]
def function_generated_table(
table_generator: Callable[..., Table | None],
source_tables: Table | Sequence[Table] | None = None,
refresh_interval_ms: int | None = None,
exec_ctx: ExecutionContext | None = None,
args: tuple = (),
kwargs: dict = {},
copy_data: bool = True,
blink_table: bool = False,
table_definition: TableDefinitionLike | None = None,
) -> Table:
"""Creates an abstract table that is generated by running the table_generator() function. The function will first be
run to generate the table when this method is called, then subsequently either (a) whenever one of the
'source_tables' ticks or (b) after refresh_interval_ms have elapsed. At most one of 'refresh_interval_ms' or
'source_tables' may be set. When neither is set there is no refresh trigger: the 'table_generator' runs exactly
once, and the result is a static table.
Function-generated tables can be used to produce dynamic tables from sources outside Deephaven. For example,
function-generated tables can create tables that are produced by arbitrary Python logic (including using Pandas or
numpy). They can also be used to retrieve data from external sources (such as files or websites).
The table definition must not change between invocations of the 'table_generator' function, or an exception will
be raised.
Every refresh in which 'table_generator' produces a table replaces the result in full: the update removes all
previous rows and adds all newly generated rows, with no modifications or shifts, even when the generated data is
identical to the previous cycle's. A refresh in which 'table_generator' returns None retains the previous result
with no update (or clears a blink result). The 'copy_data' and 'blink_table' arguments refine this behavior
independently of one another.
Note that the 'table_generator' may access data in the sourceTables but should not perform further table operations
on them without careful handling. Table operations may be memoized, and it is possible that a table operation will
return a table created by a previous invocation of the same operation. Since that result will not have been included
in the 'source_table', it's not automatically treated as a dependency for purposes of determining when it's safe to
invoke 'table_generator', allowing races to exist between accessing the operation result and that result's own
update
processing. It's best to include all dependencies directly in 'source_table', or only compute on-demand inputs under
a LivenessScope.
Args:
table_generator (Callable[..., Optional[Table]]): The table generator function. This function must return a Table, or None
to decline producing a new table, in which case the previous cycle's result is retained (or, for a blink
table, cleared). If the very first invocation returns None, 'table_definition' must be provided so the
result's columns are known.
source_tables (Optional[Union[Table, Sequence[Table]]]): Source tables used by the 'table_generator' function. The
'table_generator' is rerun when any of these tables tick.
refresh_interval_ms (Optional[int]): Interval (in milliseconds) at which the 'table_generator' function is
rerun. A non-positive interval is treated the same as no trigger at all, producing a static result.
exec_ctx (Optional[ExecutionContext]): A custom execution context. If 'None', the current
execution context is used.
args (tuple): Optional tuple of positional arguments to pass to table_generator. Defaults to ()
kwargs (dict): Optional dictionary of keyword arguments to pass to table_generator. Defaults to {}
copy_data (bool): When True (the default), the generated data is copied into the result's own column sources
and the result uses a flat, contiguous row set. When False, the result delegates directly to the generated
table's column sources, avoiding the copy and adopting the generated table's row set as-is: the added rows
of each update are the generated table's row set, and the removed rows are the previous cycle's row set. In
that case a refreshing generated table must expose immutable column sources; a generated table that changes
values in place is rejected. Defaults to True.
blink_table (bool): When True, the result is presented as a blink table, retaining only the rows generated
during the current cycle. Each update is still a full replacement; the blink attribute changes how
downstream operations interpret it and is independent of 'copy_data'. Rows generated in one update cycle
are removed on the next cycle whether or not 'table_generator' runs again. On a cycle where
'table_generator' returns None, the blink result is cleared. Requires a refresh trigger
('refresh_interval_ms' or 'source_tables'). Defaults to False.
table_definition (Optional[TableDefinitionLike]): When provided, it is authoritative: it defines the result's
columns and their order, and every table the 'table_generator' produces must be compatible with it. Defaults
to None, in which case the generated table's definition is used.
Returns:
a new table
Raises:
DHError
"""
if refresh_interval_ms is not None and source_tables is not None:
raise DHError(
"Only one of refresh_interval_ms and source_tables must be provided!"
)
# If no execution context is provided, assume we want to use the current one.
if exec_ctx is None:
exec_ctx = execution_context.get_exec_ctx()
def table_generator_function():
with exec_ctx:
result = table_generator(*args, **kwargs)
# A None result means "no new table"; the previously produced result is retained for the next cycle.
if result is None:
return _JOptional.empty()
if isinstance(result, Table) is False:
raise DHError("table_generator did not return a Table")
return _JOptional.of(result.j_table)
# Treat the table_generator_function as a Java lambda (i.e., wrap it in a Java Supplier<Optional<Table>>):
table_generator_j_function = j_lambda(table_generator_function, _JSupplier)
if isinstance(source_tables, Table):
source_tables = [source_tables]
try:
builder = _JFunctionGeneratedTableSpec.builder()
builder.retainingLastTableSupplier(table_generator_j_function)
builder.copyData(copy_data)
builder.blinkTable(blink_table)
if table_definition is not None:
builder.tableDefinition(
TableDefinition(table_definition).j_table_definition
)
if source_tables is not None:
builder.addDependencies([tbl.j_table for tbl in source_tables])
elif refresh_interval_ms is not None and refresh_interval_ms > 0:
builder.refreshInterval(_JDuration.ofMillis(refresh_interval_ms))
spec = builder.build()
if source_tables is not None:
# Create the function-generated table under a lock covering the source tables:
with auto_locking_ctx(*source_tables):
j_function_generated_table = _JFunctionGeneratedTableFactory.create(
spec
)
else:
j_function_generated_table = _JFunctionGeneratedTableFactory.create(spec)
return Table(j_function_generated_table)
except Exception as e:
raise DHError(e, "failed to create a function-generated table.") from e