## Copyright (c) 2016-2024 Deephaven Data Labs and Patent Pending#importcontextlibimportinspectimportjpyfromtypingimportDict,Union,Mapping,Optional,AnyfromdeephavenimportDHErrorfromdeephaven.tableimportTable,_j_py_script_session_JSql=jpy.get_type("io.deephaven.engine.sql.Sql")@contextlib.contextmanagerdef_scope(globals:Mapping[str,Any],locals:Mapping[str,Any]):j_py_script_session=_j_py_script_session()# Can do `globals | locals` in Python 3.9+j_py_script_session.pushScope({**globals,**locals})try:yieldfinally:j_py_script_session.popScope()
[docs]defevaluate(sql:str,dry_run:bool=False,)->Union[Table,jpy.JType]:"""Evaluates an SQL query and returns the result. The query scope is taken from the environment when this method is called. Args: sql (str): SQL query string dry_run (bool, optional): if the query should be a dry run, default is False Returns: a new Table, or a java TableSpec if dry_run is True Raises: DHError """try:callers_frame_info=inspect.stack()[1]globals=callers_frame_info.frame.f_globalslocals=callers_frame_info.frame.f_localswith_scope(globals,locals):ifdry_run:# No JObjectWrapper for TableSpecreturn_JSql.dryRun(sql)else:returnTable(j_table=_JSql.evaluate(sql))exceptExceptionase:raiseDHError(e,"failed to execute SQL.")frome