(
query: str,
connection: duckdb.DuckDBPyConnection | None,
)
| 94 | |
| 95 | |
| 96 | def wrapped_sql( |
| 97 | query: str, |
| 98 | connection: duckdb.DuckDBPyConnection | None, |
| 99 | ) -> duckdb.DuckDBPyRelation: |
| 100 | DependencyManager.duckdb.require("to execute sql") |
| 101 | import duckdb |
| 102 | |
| 103 | # In Python globals() are scoped to modules; since this function |
| 104 | # is in a different module than user code, globals() doesn't return |
| 105 | # the kernel globals, it just returns this module's global namespace. |
| 106 | # |
| 107 | # However, duckdb needs access to the kernel's globals. For this reason, |
| 108 | # we manually exec duckdb and provide it with the kernel's globals. |
| 109 | if connection is None: |
| 110 | connection = cast(duckdb.DuckDBPyConnection, duckdb) |
| 111 | |
| 112 | try: |
| 113 | ctx = get_context() |
| 114 | except ContextNotInitializedError: |
| 115 | result = _try_wasm_duckdb("sql", query, connection, globals()) |
| 116 | if result is _NO_WASM_DUCKDB_RESULT: |
| 117 | # No WASM rewrite was needed; use DuckDB's normal SQL path. |
| 118 | relation = connection.sql(query=query) |
| 119 | else: |
| 120 | relation = cast(duckdb.DuckDBPyRelation, result) |
| 121 | else: |
| 122 | install_connection = ( |
| 123 | ctx.execution_context.with_connection |
| 124 | if ctx.execution_context is not None |
| 125 | else nullcontext |
| 126 | ) |
| 127 | with install_connection(connection): |
| 128 | result = _try_wasm_duckdb( |
| 129 | "sql", |
| 130 | query, |
| 131 | connection, |
| 132 | ctx.globals, |
| 133 | ) |
| 134 | if result is _NO_WASM_DUCKDB_RESULT: |
| 135 | # Run in kernel globals so DuckDB replacement scans see user data. |
| 136 | relation = eval( |
| 137 | "connection.sql(query=query)", |
| 138 | ctx.globals, |
| 139 | {"query": query, "connection": connection}, |
| 140 | ) |
| 141 | else: |
| 142 | relation = cast(duckdb.DuckDBPyRelation, result) |
| 143 | |
| 144 | return relation |
| 145 | |
| 146 | |
| 147 | def execute_duckdb_sql( |
searching dependent graphs…