|
| 1 | +# aws_advanced_python_wrapper/sqlalchemy/sqlalchemy_psycopg_dialect.py |
| 2 | +from psycopg import Connection |
| 3 | +from sqlalchemy.dialects.postgresql.psycopg import PGDialect_psycopg |
| 4 | +import re |
| 5 | + |
| 6 | +class SqlAlchemyOrmPgDialect(PGDialect_psycopg): |
| 7 | + """ |
| 8 | + SQLAlchemy dialect for AWS Advanced Python Wrapper. |
| 9 | + Extends PostgreSQL psycopg dialect with Aurora-aware connection handling. |
| 10 | + """ |
| 11 | + |
| 12 | + name = 'postgresql' |
| 13 | + driver = 'aws_wrapper' |
| 14 | + |
| 15 | + def __init__(self, **kwargs): |
| 16 | + # Skip parent's version check since we're a wrapper, not psycopg itself |
| 17 | + super(PGDialect_psycopg, self).__init__(**kwargs) |
| 18 | + |
| 19 | + # Dynamically detect the actual psycopg version we're wrapping to ensure |
| 20 | + # SQLAlchemy uses the correct feature set and SQL generation |
| 21 | + try: |
| 22 | + import psycopg |
| 23 | + m = re.match(r"(\d+)\.(\d+)(?:\.(\d+))?", psycopg.__version__) |
| 24 | + if m: |
| 25 | + self.psycopg_version = tuple( |
| 26 | + int(x) for x in m.group(1, 2, 3) if x is not None |
| 27 | + ) |
| 28 | + else: |
| 29 | + self.psycopg_version = (3, 0, 2) # Minimum supported |
| 30 | + except (ImportError, AttributeError): |
| 31 | + self.psycopg_version = (3, 0, 2) |
| 32 | + |
| 33 | + @classmethod |
| 34 | + def import_dbapi(cls): |
| 35 | + """ |
| 36 | + Return the DB-API 2.0 module. |
| 37 | + SQLAlchemy calls this to get the driver module. |
| 38 | + """ |
| 39 | + import aws_advanced_python_wrapper |
| 40 | + return aws_advanced_python_wrapper |
| 41 | + |
| 42 | + def create_connect_args(self, url): |
| 43 | + """ |
| 44 | + Transform SQLAlchemy URL into connection arguments. |
| 45 | + Must include 'target' parameter for the wrapper. |
| 46 | + """ |
| 47 | + # Extract standard connection parameters |
| 48 | + opts = url.translate_connect_args(username='user') |
| 49 | + |
| 50 | + # Add query string parameters |
| 51 | + opts.update(url.query) |
| 52 | + |
| 53 | + # Add the required 'target' parameter for your wrapper |
| 54 | + if 'target' not in opts: |
| 55 | + opts['target'] = Connection.connect |
| 56 | + |
| 57 | + # Return empty args list and kwargs dict |
| 58 | + return ([], opts) |
| 59 | + |
| 60 | + def on_connect(self): |
| 61 | + """ |
| 62 | + Return a callable that will be executed on new connections. This can be used if we need to set any session-level |
| 63 | + parameters. |
| 64 | + """ |
| 65 | + |
| 66 | + def set_session_params(conn): |
| 67 | + # Set any Aurora-specific session parameters |
| 68 | + cursor = conn.cursor() |
| 69 | + try: |
| 70 | + # Example: Set statement timeout |
| 71 | + cursor.execute("SET statement_timeout = '60s'") |
| 72 | + finally: |
| 73 | + cursor.close() |
| 74 | + |
| 75 | + return set_session_params |
| 76 | + |
| 77 | + def get_isolation_level(self, dbapi_connection): |
| 78 | + """Get the current isolation level""" |
| 79 | + cursor = dbapi_connection.cursor() |
| 80 | + try: |
| 81 | + cursor.execute("SHOW transaction_isolation") |
| 82 | + val = cursor.fetchone() |
| 83 | + if val: |
| 84 | + # Extract first element from tuple and format |
| 85 | + return val.upper().replace(' ', '_') |
| 86 | + return 'READ_COMMITTED' # PostgreSQL's default |
| 87 | + finally: |
| 88 | + cursor.close() |
| 89 | + |
| 90 | + def initialize(self, connection): |
| 91 | + """ |
| 92 | + Override initialization to handle type introspection. |
| 93 | + The parent class tries to use TypeInfo.fetch() which requires |
| 94 | + a native psycopg connection, not our wrapper. |
| 95 | + """ |
| 96 | + # Find the AwsWrapperConnection at whatever nesting level |
| 97 | + wrapper_conn = self._get_wrapper_connection(connection) |
| 98 | + |
| 99 | + if wrapper_conn and hasattr(wrapper_conn, 'connection'): |
| 100 | + # Get the underlying psycopg connection |
| 101 | + underlying_conn = wrapper_conn.connection |
| 102 | + |
| 103 | + # Temporarily swap the entire connection chain |
| 104 | + original_dbapi_conn = connection.connection |
| 105 | + connection.connection = underlying_conn |
| 106 | + |
| 107 | + try: |
| 108 | + # Call parent initialization with native psycopg connection |
| 109 | + super().initialize(connection) |
| 110 | + finally: |
| 111 | + # Restore original connection chain |
| 112 | + connection.connection = original_dbapi_conn |
| 113 | + else: |
| 114 | + # If we can't find wrapper or it doesn't expose underlying connection, |
| 115 | + # skip type introspection (custom types won't be auto-configured) |
| 116 | + pass |
| 117 | + |
| 118 | + def _get_wrapper_connection(self, connection): |
| 119 | + """ |
| 120 | + Traverse the connection chain to find AwsWrapperConnection. |
| 121 | + Handles variable nesting depths depending on pool configuration. |
| 122 | + """ |
| 123 | + from aws_advanced_python_wrapper import AwsWrapperConnection |
| 124 | + |
| 125 | + # Start with the DBAPI connection |
| 126 | + current = connection.connection |
| 127 | + |
| 128 | + # Traverse up to 5 levels deep (reasonable limit) |
| 129 | + for _ in range(5): |
| 130 | + if isinstance(current, AwsWrapperConnection): |
| 131 | + return current |
| 132 | + |
| 133 | + # Try to go deeper if there's a .connection attribute |
| 134 | + if hasattr(current, 'connection'): |
| 135 | + current = current.connection |
| 136 | + else: |
| 137 | + break |
| 138 | + |
| 139 | + return None |
0 commit comments