BentsiLeviav commented on code in PR #72768:
URL: https://github.com/apache/airflow/pull/72768#discussion_r4397909638


##########
providers/clickhousedb/docs/operators/clickhouse.rst:
##########
@@ -77,3 +77,40 @@ To return something other than the full result set, pass a 
custom ``handler``. F
     ``session_settings`` passed to 
:class:`~airflow.providers.clickhousedb.hooks.clickhouse.ClickHouseHook`
     directly (via ``hook_params``) take precedence over any 
``session_settings`` defined in the
     connection's ``extra`` JSON field. Conflicting keys are resolved in favor 
of the constructor argument.
+
+Multi-statement SQL and sessions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+All statements of one ``SQLExecuteQueryOperator`` task run in the same 
ClickHouse session, so temporary tables
+and ``SET`` statements carry over to the statements after them:
+
+.. code-block:: python
+
+  SQLExecuteQueryOperator(
+      task_id="list_example_rows",
+      conn_id="clickhouse_default",
+      sql=[
+          "SET max_threads = 4",
+          """
+      CREATE TEMPORARY TABLE airflow_example (
+          id   UInt32,
+          name String,
+          ts   DateTime DEFAULT now()
+      ) ENGINE = MergeTree()
+      ORDER BY id
+      """,
+          """
+      INSERT INTO airflow_example (id, name) VALUES
+          (1, 'Alice'),
+          (2, 'Bob'),
+          (3, 'Charlie')
+      """,
+          "SELECT id, name FROM airflow_example ORDER BY id",
+      ],
+  )
+
+Each task run, including a retry, gets a fresh session. Sessions live on a 
single ClickHouse

Review Comment:
   Could we use a different wording here? That is only right for 
`SQLExecuteQueryOperator`, but not for a `PythonOperator` that calls 
`hook.run()` 



##########
providers/clickhousedb/src/airflow/providers/clickhousedb/hooks/clickhouse.py:
##########
@@ -84,6 +85,49 @@ def _build_client_name(custom: str | None = None) -> str:
     return name
 
 
+def _uses_session_per_connection(client_kwargs: dict[str, Any]) -> bool:
+    """
+    Return whether :meth:`ClickHouseHook.get_conn` should open a session per 
connection.
+
+    False if ``autogenerate_session_id`` or ``session_id`` is set, or sessions 
are off globally.
+    """
+    if "autogenerate_session_id" in client_kwargs or 
client_kwargs.get("session_id"):
+        return False
+    if "session_id" in (client_kwargs.get("settings") or {}):
+        return False
+    from clickhouse_connect import common
+
+    return bool(common.get_setting("autogenerate_session_id"))
+
+
+class _SessionBoundClient:

Review Comment:
   Suggestion, not a blocker: instead of a wrapper that pretends to be a 
`Client`, could this be a small `Cursor` subclass?
   
   `Cursor.execute()` and `executemany()` already take a `settings` argument. A 
subclass that puts `session_id` into that argument and calls the parent would 
touch only the two methods Airflow actually uses. That removes the 
`__getattr__` pass-through, the `cast(...)` on line 166, and the gap where any 
client method not listed here runs without the session.



##########
providers/clickhousedb/docs/operators/clickhouse.rst:
##########
@@ -77,3 +77,40 @@ To return something other than the full result set, pass a 
custom ``handler``. F
     ``session_settings`` passed to 
:class:`~airflow.providers.clickhousedb.hooks.clickhouse.ClickHouseHook`
     directly (via ``hook_params``) take precedence over any 
``session_settings`` defined in the
     connection's ``extra`` JSON field. Conflicting keys are resolved in favor 
of the constructor argument.
+
+Multi-statement SQL and sessions
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+All statements of one ``SQLExecuteQueryOperator`` task run in the same 
ClickHouse session, so temporary tables
+and ``SET`` statements carry over to the statements after them:
+
+.. code-block:: python
+
+  SQLExecuteQueryOperator(
+      task_id="list_example_rows",
+      conn_id="clickhouse_default",
+      sql=[
+          "SET max_threads = 4",
+          """
+      CREATE TEMPORARY TABLE airflow_example (
+          id   UInt32,
+          name String,
+          ts   DateTime DEFAULT now()
+      ) ENGINE = MergeTree()
+      ORDER BY id
+      """,
+          """
+      INSERT INTO airflow_example (id, name) VALUES
+          (1, 'Alice'),
+          (2, 'Bob'),
+          (3, 'Charlie')
+      """,
+          "SELECT id, name FROM airflow_example ORDER BY id",
+      ],
+  )
+
+Each task run, including a retry, gets a fresh session. Sessions live on a 
single ClickHouse
+server, so if a load balancer can route one task's statements to different 
servers, set

Review Comment:
   For CH cloud users, could we state that temporary tables are unreliable on 
Cloud without stickiness? 



##########
providers/clickhousedb/src/airflow/providers/clickhousedb/hooks/clickhouse.py:
##########
@@ -131,6 +185,16 @@ class ClickHouseHook(DbApiHook):
     features work out of the box (templating, ``handler``, 
``split_statements``,
     etc.).
 
+    The client is created lazily on first use and reused for the lifetime of 
the

Review Comment:
   Small points that are missing for me that might be useful to add:
   
   1. Don't close the client from get_client() - The 1.0.x docstring told 
callers to close it. Readers coming from that version need to hear the opposite 
here.
   2. bulk_insert_rows() uses the shared client too. So it also has no session. 
The changelog says this; should we add it to the docstring as well?
   3. Load balancers and ClickHouse Cloud. Sessions only work when all 
statements reach the same server. Adding one sentence pointing to the operator 
docs section would save Cloud users a confusing afternoon.



##########
providers/clickhousedb/src/airflow/providers/clickhousedb/hooks/clickhouse.py:
##########
@@ -185,6 +249,8 @@ def __init__(
         self.database = database
         self.session_settings: dict[str, Any] = session_settings or {}
         self.client_kwargs: dict[str, Any] = client_kwargs or {}
+        self._client: clickhouse_connect.driver.client.Client | None = None
+        self._session_per_connection: bool = True

Review Comment:
   Small design point: this `True` is a placeholder that `_get_client_kwargs()` 
overwrites as a side effect, so the kwargs builder also mutates hook state. If 
anything sets `self._client` without going through it (a subclass overriding 
`get_client()`, or a test assigning the client), `get_conn()` keeps the 
placeholder and injects a per-connection session even when the user configured 
their own.
   
   Could the flag be computed in `get_client()` from the same kwargs dict that 
is passed to `clickhouse_connect.get_client()`? Then the builder stays pure and 
the flag can't drift from the client it describes.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to