jason810496 commented on code in PR #51056:
URL: https://github.com/apache/airflow/pull/51056#discussion_r2107440538


##########
providers/postgres/src/airflow/providers/postgres/triggers/postgres_cdc.py:
##########
@@ -0,0 +1,125 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+import asyncio
+import datetime
+from collections.abc import AsyncGenerator
+from datetime import timezone
+
+import psycopg2
+
+from airflow.hooks.base import BaseHook
+from airflow.models import Variable
+from airflow.triggers.base import BaseEventTrigger, TriggerEvent
+
+
+class PostgresCDCEventTrigger(BaseEventTrigger):
+    """
+    A trigger that waits for changes in a PostgreSQL table using polling over 
a timestamp/version column.
+
+    The behavior of this trigger is as follows:
+    - Poll the target table using `SELECT MAX(cdc_column)`.
+    - Compare the result with the stored "last read" value (persisted as an 
Airflow Variable).
+    - If a new value is found (greater than last read), emit a TriggerEvent 
containing metadata.
+    - If no new value is found, sleep for `polling_interval` seconds and 
continue polling.
+
+    :param conn_id: Airflow connection ID for PostgreSQL.
+    :param table: Name of the table to monitor.
+    :param cdc_column: Column representing the change timestamp or version.
+    :param polling_interval: Time (seconds) between polling attempts (default: 
10.0).
+    :param state_key: Key used for persisting CDC state. If None, defaults to 
`{table}_cdc_last_value`.
+    """
+
+    def __init__(
+        self,
+        conn_id: str,
+        table: str,
+        cdc_column: str,
+        polling_interval: float = 10.0,
+        state_key: str | None = None,
+    ):
+        super().__init__()
+        self.conn_id = conn_id
+        self.table = table
+        self.cdc_column = cdc_column
+        self.polling_interval = polling_interval
+        self.state_key = state_key or f"{self.table}_cdc_last_value"
+
+    def serialize(self) -> tuple[str, dict]:
+        """Serialize the trigger's configuration for persistence and 
reconstruction."""
+        return (
+            
"airflow.providers.postgres.triggers.postgres_cdc.PostgresCDCEventTrigger",
+            {
+                "conn_id": self.conn_id,
+                "table": self.table,
+                "cdc_column": self.cdc_column,
+                "polling_interval": self.polling_interval,
+                "state_key": self.state_key,
+            },
+        )
+
+    async def run(self) -> AsyncGenerator[TriggerEvent, None]:
+        """Run the asynchronous polling loop to detect new changes in the 
monitored table."""
+        conn = BaseHook.get_connection(self.conn_id)
+
+        while True:
+            try:
+                with psycopg2.connect(
+                    host=conn.host,
+                    port=conn.port,
+                    dbname=conn.schema,
+                    user=conn.login,
+                    password=conn.password,
+                ) as pg_conn:
+                    with pg_conn.cursor() as cursor:
+                        cursor.execute(f"SELECT MAX({self.cdc_column}) FROM 
{self.table}")
+                        result = cursor.fetchone()
+                        max_value: datetime.datetime | None = result[0]
+
+                        if max_value is not None:

Review Comment:
   I think we could flatten the `max_value` criteria with early return:
   ```python
   if not max_value:
       self.log.info("No data found in %s for column %s.", self.table, 
self.cdc_column)
       return
   
   # ... rest of logic
   ```



##########
providers/postgres/src/airflow/providers/postgres/triggers/postgres_cdc.py:
##########
@@ -0,0 +1,125 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+import asyncio
+import datetime
+from collections.abc import AsyncGenerator
+from datetime import timezone
+
+import psycopg2
+
+from airflow.hooks.base import BaseHook
+from airflow.models import Variable
+from airflow.triggers.base import BaseEventTrigger, TriggerEvent
+
+
+class PostgresCDCEventTrigger(BaseEventTrigger):
+    """
+    A trigger that waits for changes in a PostgreSQL table using polling over 
a timestamp/version column.
+
+    The behavior of this trigger is as follows:
+    - Poll the target table using `SELECT MAX(cdc_column)`.
+    - Compare the result with the stored "last read" value (persisted as an 
Airflow Variable).
+    - If a new value is found (greater than last read), emit a TriggerEvent 
containing metadata.
+    - If no new value is found, sleep for `polling_interval` seconds and 
continue polling.
+
+    :param conn_id: Airflow connection ID for PostgreSQL.
+    :param table: Name of the table to monitor.
+    :param cdc_column: Column representing the change timestamp or version.
+    :param polling_interval: Time (seconds) between polling attempts (default: 
10.0).
+    :param state_key: Key used for persisting CDC state. If None, defaults to 
`{table}_cdc_last_value`.
+    """
+
+    def __init__(
+        self,
+        conn_id: str,
+        table: str,
+        cdc_column: str,
+        polling_interval: float = 10.0,
+        state_key: str | None = None,
+    ):
+        super().__init__()
+        self.conn_id = conn_id
+        self.table = table
+        self.cdc_column = cdc_column
+        self.polling_interval = polling_interval
+        self.state_key = state_key or f"{self.table}_cdc_last_value"
+
+    def serialize(self) -> tuple[str, dict]:
+        """Serialize the trigger's configuration for persistence and 
reconstruction."""
+        return (
+            
"airflow.providers.postgres.triggers.postgres_cdc.PostgresCDCEventTrigger",
+            {
+                "conn_id": self.conn_id,
+                "table": self.table,
+                "cdc_column": self.cdc_column,
+                "polling_interval": self.polling_interval,
+                "state_key": self.state_key,
+            },
+        )
+
+    async def run(self) -> AsyncGenerator[TriggerEvent, None]:

Review Comment:
   ```suggestion
       async def run(self) -> AsyncGenerator[TriggerEvent]:
   ```



##########
providers/postgres/tests/system/postgres/example_postgres_cdc_asset_watcher.py:
##########
@@ -0,0 +1,97 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+import psycopg2
+
+from airflow.hooks.base import BaseHook
+from airflow.models import Variable
+from airflow.providers.postgres.triggers.postgres_cdc import 
PostgresCDCEventTrigger
+from airflow.sdk import DAG, Asset, AssetWatcher, task
+
+"""
+Example DAG that demonstrates how to use the PostgresCDCEventTrigger.
+
+This DAG sets up an AssetWatcher linked to a PostgreSQL CDC trigger, which 
monitors changes
+in a specific table based on a timestamp column (`cdc_column`). When a change 
is detected, it executes a task
+that processes new rows and updates the Airflow Variable used to track CDC 
state (`state_key`).
+
+The state variable is configurable via `state_key`.
+"""
+
+STATE_KEY = "my_table_cdc_last_value"
+
+cdc_trigger = PostgresCDCEventTrigger(
+    conn_id="postgres_default",
+    table="my_table",
+    cdc_column="updated_at",
+    polling_interval=20,
+    state_key=STATE_KEY,
+)
+
+cdc_asset = Asset(
+    "postgres_cdc_asset", watchers=[AssetWatcher(name="postgres_cdc_watcher", 
trigger=cdc_trigger)]
+)
+
+with DAG(
+    dag_id="example_postgres_cdc_watcher",
+    schedule=[cdc_asset],
+    catchup=False,
+    max_active_runs=1,
+) as dag:
+
+    @task
+    def extract_and_update_last_value():
+        """
+        Extracts new rows from the monitored table that have `updated_at` 
greater than the
+        last recorded value in Airflow Variable, then updates the Variable 
with the new maximum.
+        """
+        conn = BaseHook.get_connection("postgres_default")
+
+        with psycopg2.connect(
+            host=conn.host, port=conn.port, dbname=conn.schema, 
user=conn.login, password=conn.password
+        ) as pg_conn:
+            with pg_conn.cursor() as cursor:
+                last_value = Variable.get(STATE_KEY, default_var=None)

Review Comment:
   How about having a `state_key` readonly property in 
`PostgresCDCEventTrigger`, so that user can get last value with:
   ```python
   last_value = Variable.get(cdc_trigger.state_key, default_var=None)
   ```



##########
providers/postgres/src/airflow/providers/postgres/triggers/postgres_cdc.py:
##########
@@ -0,0 +1,125 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+from __future__ import annotations
+
+import asyncio
+import datetime
+from collections.abc import AsyncGenerator
+from datetime import timezone
+
+import psycopg2
+
+from airflow.hooks.base import BaseHook
+from airflow.models import Variable
+from airflow.triggers.base import BaseEventTrigger, TriggerEvent
+
+
+class PostgresCDCEventTrigger(BaseEventTrigger):
+    """
+    A trigger that waits for changes in a PostgreSQL table using polling over 
a timestamp/version column.
+
+    The behavior of this trigger is as follows:
+    - Poll the target table using `SELECT MAX(cdc_column)`.
+    - Compare the result with the stored "last read" value (persisted as an 
Airflow Variable).
+    - If a new value is found (greater than last read), emit a TriggerEvent 
containing metadata.
+    - If no new value is found, sleep for `polling_interval` seconds and 
continue polling.
+
+    :param conn_id: Airflow connection ID for PostgreSQL.
+    :param table: Name of the table to monitor.
+    :param cdc_column: Column representing the change timestamp or version.
+    :param polling_interval: Time (seconds) between polling attempts (default: 
10.0).
+    :param state_key: Key used for persisting CDC state. If None, defaults to 
`{table}_cdc_last_value`.
+    """
+
+    def __init__(
+        self,
+        conn_id: str,
+        table: str,
+        cdc_column: str,
+        polling_interval: float = 10.0,
+        state_key: str | None = None,
+    ):
+        super().__init__()
+        self.conn_id = conn_id
+        self.table = table
+        self.cdc_column = cdc_column
+        self.polling_interval = polling_interval
+        self.state_key = state_key or f"{self.table}_cdc_last_value"
+
+    def serialize(self) -> tuple[str, dict]:
+        """Serialize the trigger's configuration for persistence and 
reconstruction."""
+        return (
+            
"airflow.providers.postgres.triggers.postgres_cdc.PostgresCDCEventTrigger",
+            {
+                "conn_id": self.conn_id,
+                "table": self.table,
+                "cdc_column": self.cdc_column,
+                "polling_interval": self.polling_interval,
+                "state_key": self.state_key,
+            },
+        )
+
+    async def run(self) -> AsyncGenerator[TriggerEvent, None]:
+        """Run the asynchronous polling loop to detect new changes in the 
monitored table."""
+        conn = BaseHook.get_connection(self.conn_id)
+
+        while True:
+            try:
+                with psycopg2.connect(
+                    host=conn.host,
+                    port=conn.port,
+                    dbname=conn.schema,
+                    user=conn.login,
+                    password=conn.password,
+                ) as pg_conn:
+                    with pg_conn.cursor() as cursor:

Review Comment:
   How about using existed `PostgresHook` to establish connection ?



-- 
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