jose-lehmkuhl commented on code in PR #51056: URL: https://github.com/apache/airflow/pull/51056#discussion_r2107692635
########## 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: I've updated the code to use PostgresHook.get_conn() instead of psycopg2. Makes it cleaner and more consistent with Airflow patterns. Thanks! -- 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]
