`CTAS` that works in the Redshift query editor fails when run via a `PostgresHook` in MWAA due to mixed-case field

TL;DR

A CTAS that works when run in the Redshift query editor fails when passed to Redshift via a PostgresHook in Airflow because of weirdness with a case-sensitive field in an external (RDS) table.

The issue

I’m building a small pipeline on Redshift using Airflow 2.7.2 on AWS MWAA.

I’m using PythonOperator to manage a transaction for a simple transform on data from an external schema connected to RDS. The transform part of the transaction looks like this:

create table "ops_qms_dev"."rem_publication_hx" as 
with rem_publication_sitegroups_1yr as ( 
    select 
        id,
        "itemType"::varchar(256) as item_type,
        "itemId"::varchar(36) as site_group_id,
        event::varchar(256), 
        owner, object, "timestamp" 
    from "ext_next_gen"."version"
    where 
        true 
        and "itemType" = 'SiteGroup' 
        and event = 'UPDATE' and 
        json_extract_path_text(owner, 'handler') in ( 
            'publishRem', 
            'promoteSiteGroupWorkingRems'
        ) 
        and "timestamp"::date > current_date - '1 year'::interval 
) 

select * from rem_publication_sitegroups_1yr;

It fails when run from the Airflow DAG with the following error:

psycopg2.errors.InternalError_: column "itemtype" does not exist
DETAIL:  
  -----------------------------------------------
  error:  column "itemtype" does not exist
  code:      25300
  context:   
  query:     219700193
  location:  pgclient.cpp:908
  process:   query1_101_219700193 [pid=7610]
  -----------------------------------------------

Which looks like the error I’d expect if the mixed-case column name weren’t properly double-quoted.

What I’ve tried

  • I’ve run the statement verbatim from an external SQL client, and it runs successfully
  • I’ve removed the mixed-case columns from the query and run the DAG in Airflow successfully
  • I’ve looked at stl_query for the offending query from Airflow, and confirmed that the querytxt is exactly as I passed it (with properly double-quoted, mixed-case columns where expected)
  • I’ve tried creating a SQLAlchemy connection from the PostgresHook to see if a different engine would issue with psycopg2, but got the same error.

Some additional code for reference

Here’s my python callable:

def build_qms_pipeline_table(table, ctas):
    """Build a table in the QMS schema using a CTAS query, all wrapped in a transaction."""
    redshift_hook = PostgresHook(postgres_conn_id="prod-monitoring-analytics")
    conn = redshift_hook.get_conn()
    _build_qms_pipeline_table(table, ctas, conn)


def _build_qms_pipeline_table(table, ctas, conn):
    fully_qualified_table = f'"{OPS_QMS_SCHEMA}"."{table}"'
    with conn:
        with conn.cursor() as cursor:
            try:
                logger.info(f"Building {fully_qualified_table}...")
                cursor.execute("begin;")
                cursor.execute(f"drop table if exists {fully_qualified_table} cascade;")
                create_table_query = f"create table {fully_qualified_table} as {ctas};"
                cursor.execute(create_table_query)
                cursor.execute("commit;")
                logger.info(f"Success on {fully_qualified_table}")
            except Exception as e:
                logger.error(f"Build failed; rolling back for {fully_qualified_table}...")
                cursor.execute("rollback;")
                raise e

My attempt at a SQLAlchemy connection:

def build_qms_pipeline_table(table, ctas):
    """Build a table in the QMS schema using a CTAS query, all wrapped in a transaction."""
    redshift_hook = PostgresHook(postgres_conn_id="redshift-conn")
    with create_engine(redshift_hook.get_uri()).connect() as conn:
        _build_qms_pipeline_table(table, ctas, conn)


def _build_qms_pipeline_table(table, ctas, conn):
    fully_qualified_table = f'"{OPS_QMS_SCHEMA}"."{table}"'
    trans = conn.begin()
    try:
        logger.info(f"Building {fully_qualified_table}...")
        conn.execute(text(f"drop table if exists {fully_qualified_table} cascade;"))
        create_table_query = text(f"create table {fully_qualified_table} as {ctas};")
        conn.execute(create_table_query)
        trans.commit()
        logger.info(f"Success on {fully_qualified_table}")
    except Exception as e:
        logger.error(f"Build failed; rolling back for {fully_qualified_table}...")
        trans.rollback()
        raise e

The DAG task

    build_rem_publication_hx = PythonOperator(
        task_id="build_rem_publication_hx",
        python_callable=build_qms_pipeline_table,
        op_kwargs={
            "table": "rem_publication_hx",
            "ctas": REM_PUBLICATION_HX_CTAS.read_text(),
        },
        provide_context=True,
        dag=dag,
    )

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật