') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); Allow keeping PostgresHook SQLAlchemy engines on psycopg2 by sehajsandhu123 · Pull Request #72000 · apache/airflow · GitHub
Skip to content

Allow keeping PostgresHook SQLAlchemy engines on psycopg2 - #72000

Open
sehajsandhu123 wants to merge 4 commits into
apache:mainfrom
sehajsandhu123:postgres-hook-sqlalchemy-scheme
Open

Allow keeping PostgresHook SQLAlchemy engines on psycopg2#72000
sehajsandhu123 wants to merge 4 commits into
apache:mainfrom
sehajsandhu123:postgres-hook-sqlalchemy-scheme

Conversation

@sehajsandhu123

@sehajsandhu123sehajsandhu123 commented Aug 23, 2026

Copy link
Copy Markdown

Since postgres provider 7.0.0, PostgresHook builds its SQLAlchemy engines on psycopg (v3) whenever SQLAlchemy 2.x is installed, and the 7.0.0 changelog notes there is no connection or configuration option to keep hooks on psycopg2.

This silently changes semantics for Dag code that uses hook.get_uri() or hook.get_sqlalchemy_engine(). The psycopg (v3) dialect renders typed bind casts, so string parameters that PostgreSQL used to coerce implicitly now fail server-side. The most common casualty is pandas.DataFrame.to_sql into a table with a uuid column, which worked for years on psycopg2 and now fails with:

psycopg.errors.DatatypeMismatch: column "id" is of type uuid but expression is of type character varying
LINE 1: INSERT INTO orders (id, item) VALUES ($1::VARCHAR, $2...

This PR adds the missing opt-out by honoring the sqlalchemy_scheme connection extra (and an equivalent hook parameter), the same convention OdbcHook and DbApiHook.dialect_name already follow. PostgresHook even lists sqlalchemy_scheme in ignored_extra_options, so it is already excluded from libpq connect args — it just wasn't used when building the URL. With this change, a connection that needs the old behaviour can set:

{"sqlalchemy_scheme": "postgresql+psycopg2"}

The value is validated to be postgresql or postgresql+<driver> with no : or /, so a connection extra can't smuggle in a different URL. Nothing changes for connections that don't set it.

Tested against PostgreSQL 17 with pandas 3.0.5 / SQLAlchemy 2.0.51: df.to_sql into a uuid column reproduces the error above on the default psycopg3 engine and succeeds with the extra set. Unit tests cover the override, parameter precedence, get_uri propagation, and rejection of invalid schemes.

related: #71977


Was generative AI tooling used to co-author this PR?
  • Yes — Claude Code (Fable 5); all changes reviewed and validated by the author

Generated-by: Claude Code (Fable 5) following the guidelines

@boring-cyborg

Copy link
Copy Markdown

Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide
Here are some useful points:

  • Pay attention to the quality of your code (ruff, mypy and type annotations). Our prek-hooks will help you with that.
  • In case of a new feature add useful documentation (in docstrings or in docs/ directory). Adding a new operator? Check this short guide Consider adding an example Dag that shows how users should use it.
  • Consider using Breeze environment for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
  • Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
  • Please follow ASF Code of Conduct for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
  • Be sure to read the Airflow Coding style.
  • Always keep your Pull Requests rebased, otherwise your build might fail due to changes not related to your commits.
    Apache Airflow is a community-driven project and together we are making it better 🚀.
    In case of doubts contact the developers at:
    Mailing List: dev@airflow.apache.org
    Slack: https://s.apache.org/airflow-slack

@Dev-iLDev-iL left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation looks correct and the tests are helpful.

I'm conflicted about whether we want to support this functionality. On the one hand, we should be careful about adding workarounds for the behavior of other libraries. On the other hand, because this an explicit, non-default escape hatch for users migrating to ppg3, it might be justified.

My main request is related to regression tests: please ensure CI reproduces the pandas DataFrame.to_sql() -> uuid failure with ppg3 (via an xfail test) but passes on ppg2.

Please include links to any upstream pandas/SQLAlchemy discussions or issues related to this topic so we can track whether this remains necessary long-term. Examples:

There is no connection or configuration option to keep hooks on psycopg2; the
``sql_alchemy_conn`` workarounds above cover the metadata database only. If your Dags rely on
psycopg2-specific behaviour, test before upgrading or pin the provider below 7.0.0.
Starting with provider 7.1.0, the SQLAlchemy engines built by the hook can be kept on

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@eladkal Do we have a placeholder for "next feature/bugfix version" for providers? One cannot know reliably in which release a feature might be included.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Dev-iL yeah, I shouldn't have edited the changelog note.

I've removed the 7.1.0 line now. The extra param is documented in connections/postgres.rst. whenever this actually ships, that release can mention it.

@sehajsandhu123

Copy link
Copy Markdown
Author

@Dev-iL Thanks for the review, I've added the requested regression test and upstream discussion links.

I understand the caution, but this is an opt-in param, off by default. And it isn't really a new one — the convention already exists in the codebase: OdbcHook and MsSqlHook both support sqlalchemy_scheme for per-connection driver choice (pymssql vs pyodbc), and MySqlHook does the same through its client extra.

Also, the 7.0.0 notes already give the metadata DB an explicit psycopg2 opt-out via sql_alchemy_conn — hook connections were the only part of this migration without one. Since it's off by default and the strict xfail will tell us when upstream makes it unnecessary, it should be easy to retire too.

Provider 7.0.0 switched hook-built SQLAlchemy engines to psycopg (v3)
whenever SQLAlchemy 2.x is installed, with no opt-out. The psycopg
dialect renders typed bind casts, so string parameters PostgreSQL
previously coerced implicitly now fail server-side — most visibly
pandas.DataFrame.to_sql into uuid columns (apache#71977). Honor the existing
DbApiHook sqlalchemy_scheme connection extra (and hook parameter) so
connections that rely on psycopg2 behaviour can keep it.
@sehajsandhu123
sehajsandhu123force-pushed the postgres-hook-sqlalchemy-scheme branch from 7ea1579 to 4f717deCompareAugust 28, 2026 09:59
conn.login, conn.password, conn.port = self.get_iam_token(conn)
return URL.create(
drivername="postgresql+psycopg" if USE_PSYCOPG3 else "postgresql",
drivername=self.sqlalchemy_scheme,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if this should be an operator/hook parameter or something defined inside the Connection itself.

What was your thinking for putting it here?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ashb It's primarily a connection property, the hook param is just an override on top. The intended usage is setting it once on the connection (or not setting it at all is also fine, for backwards compatibility) and the hook param only kicks in if explicitly passed.

The reason I added it is if most dags on a connection are fine on psycopg3 and only one or two break, it pins just those tasks instead of rolling the whole connection back to psycopg2. Keeps the opt-out small and lets the connection default move forward.

Happy to drop the hook param if you just want the connection extra.

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@sehajsandhu123@ashb@Dev-iL