vaefremov95 opened a new issue, #77606:
URL: https://github.com/apache/airflow/issues/77606

   ### Description
   
   
   ## Problem
   
   There is no operator in the Airflow providers for moving a large query 
result from one PostgreSQL database to another.
   
   The closest built-in option is `GenericTransfer` (common-sql). It reads with 
`get_records` and writes with `insert_rows`. Its docs describe it as meant for 
"small-ish datasets that fit in memory". In paginated mode it uses 
`LIMIT/OFFSET`, which needs a stable ORDER BY and gets slower with every page. 
It has no COPY path.
   
   In practice, anything above a few million rows is moved with custom code: 
dump to a file and load it back, or hand-written `PythonOperator` + psycopg. 
This seems to be repeated in many DAG repositories.
   
   ## Idea
   
   An operator that connects `COPY ... TO STDOUT` on the source directly to 
`COPY ... FROM STDIN` on the destination and passes the bytes through in blocks:
   
   - no row materialization and no intermediate file or object storage;
   - memory stays flat regardless of table size; throughput is bounded by the 
slower side;
   - arrays, json, etc. do not need casts in SQL: COPY serializes them itself;
   - works with any database speaking the PostgreSQL COPY protocol (we use it 
with PostgreSQL and Greenplum).
   
   A similar operator has been running in production at our company for a 
while, and it has worked well for us. I am not proposing to merge it as is. 
Below is a simplified variant, just to make the idea concrete. The design, 
names and details are open for discussion.
   
   ## Variant of the code (simplified, for illustration)
   
       import logging as log
   
       import psycopg
       from airflow.sdk import BaseOperator
   
   
       def pg_uri(conn_id):
           # one possible way to connect: libpq keyword string from the Airflow 
connection
           from airflow.sdk import BaseHook
   
           c = BaseHook.get_connection(conn_id)
           return (
               f"host={c.host} port={c.port} dbname={c.schema} "
               f"user={c.login} password={c.password}"
           )
   
   
       class PostgresToPostgresOperator(BaseOperator):
           template_fields = ("sql_params", "postgres_sql__from")
           template_ext = (".sql",)
           template_fields_renderers = {"postgres_sql__from": "sql"}
   
           def __init__(
               self,
               postgres_conn_id__from,
               postgres_sql__from: str,
               postgres_conn_id__to,
               postgres_schema__to,
               postgres_table__to,
               sql_params=None,
               truncate_table__to=True,
               *args,
               **kwargs,
           ):
               super().__init__(*args, **kwargs)
               self.postgres_conn_id__from = postgres_conn_id__from
               self.postgres_sql__from = postgres_sql__from
               self.postgres_conn_id__to = postgres_conn_id__to
               self.postgres_schema__to = postgres_schema__to
               self.postgres_table__to = postgres_table__to
               self.sql_params = sql_params
               self.truncate_table__to = truncate_table__to
   
           def _load(self):
               tgt_table = 
f'{self.postgres_schema__to}."{self.postgres_table__to}"'
               copy_out_sql = f"COPY ({self.postgres_sql__from}) TO STDOUT WITH 
(FORMAT CSV, DELIMITER '\t')"
               copy_in_sql = f"COPY {tgt_table} FROM STDIN WITH (FORMAT CSV, 
DELIMITER '\t')"
   
               with (
                   psycopg.connect(pg_uri(self.postgres_conn_id__from)) as 
src_conn,
                   psycopg.connect(pg_uri(self.postgres_conn_id__to)) as 
tgt_conn,
               ):
                   with src_conn.cursor() as src_cur, tgt_conn.cursor() as 
tgt_cur:
                       with (
                           src_cur.copy(copy_out_sql) as reader,
                           tgt_cur.copy(copy_in_sql) as writer,
                       ):
                           for chunk in reader:
                               writer.write(chunk)
                       rows = tgt_cur.rowcount
                   tgt_conn.commit()
   
               log.info(f"Load finished. Rows: {rows}")
   
           def execute(self, context):
               from airflow.providers.postgres.hooks.postgres import 
PostgresHook
   
               if self.truncate_table__to:
                   PostgresHook(self.postgres_conn_id__to).run(
                       f'truncate 
{self.postgres_schema__to}."{self.postgres_table__to}"'
                   )
   
               self._load()
   
   Requires psycopg3 on the worker. Connection handling is the least important 
part here: it can be done through `PostgresHook` or any other way the 
maintainers prefer.
   
   ## Parameters
   
   | Parameter | Templated | Description |
   |---|---|---|
   | `postgres_conn_id__from` | no | Connection to the source database. |
   | `postgres_sql__from` | yes | SELECT executed on the source. Must not end 
with `;` because it is wrapped into `COPY (...)`. `.sql` files are supported 
via `template_ext`. |
   | `postgres_conn_id__to` | no | Connection to the destination database. |
   | `postgres_schema__to` | no | Destination schema. |
   | `postgres_table__to` | no | Destination table. |
   | `sql_params` | yes | Dict of values used in the query text, see below. |
   | `truncate_table__to` | no | Truncate the destination table before loading. 
Default `True`. |
   
   The names could be aligned with `GenericTransfer` (`source_conn_id`, 
`destination_conn_id`, `sql`, `destination_table`, `preoperator`).
   
   ### Why `sql_params`, and why it must be first in `template_fields`
   
   Airflow's `params` are not templated, so a Jinja expression cannot be put 
into them. `sql_params` is a templated field, so its values can be Jinja 
expressions of the task context.
   
   This is convenient when the same value is needed in many places of a query. 
The template is defined once, and the query only refers to the result:
   
       PostgresToPostgresOperator(
           task_id="load",
           postgres_conn_id__from="src",
           postgres_conn_id__to="dst",
           postgres_schema__to="public",
           postgres_table__to="events",
           sql_params={
               "date_from": "{{ ds }}",
               "date_to": "{{ macros.ds_add(ds, 1) }}",
           },
           postgres_sql__from="""
               SELECT *
               FROM events
               WHERE dt >= '{{ task.sql_params.date_from }}'
                 AND dt <  '{{ task.sql_params.date_to }}'
           """,
       )
   
   This works only if `sql_params` is rendered before the SQL. Airflow renders 
`template_fields` in the order they are listed and stores each rendered value 
back on the operator. `task` in the Jinja context is the operator itself, so 
`task.sql_params.date_from` holds the final value only when `sql_params` comes 
first. If the SQL were rendered first, `{{ task.sql_params.date_from }}` would 
still contain the raw string `{{ ds }}`, and unrendered template text would end 
up in the query.
   
   The same `.sql` file can also be reused by different DAGs with different 
`sql_params`.
   
   
   ## Questions for discussion
   
   - Is there interest in such an operator at all?
   - Where should it live: the postgres provider, or common-sql (e.g. a bulk 
path for `GenericTransfer`)?
   
   
   If there is interest, I am happy to help move this forward in whatever form 
fits best.
   
   ### Use case/motivation
   
   _No response_
   
   ### Related issues
   
   _No response_
   
   ### Are you willing to submit a PR?
   
   - [ ] Yes I am willing to submit a PR!
   
   ### Code of Conduct
   
   - [x] I agree to follow this project's [Code of 
Conduct](https://github.com/apache/airflow/blob/main/CODE_OF_CONDUCT.md)
   


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