|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"). |
| 4 | +# You may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + from aws_advanced_python_wrapper.pep249 import Connection |
| 21 | + |
| 22 | +import mysql.connector # type: ignore |
| 23 | + |
| 24 | +from aws_advanced_python_wrapper import AwsWrapperConnection |
| 25 | +from aws_advanced_python_wrapper.errors import ( |
| 26 | + FailoverFailedError, FailoverSuccessError, |
| 27 | + TransactionResolutionUnknownError) |
| 28 | + |
| 29 | +def configure_initial_session_states(conn: Connection): |
| 30 | + awscursor = conn.cursor() |
| 31 | + awscursor.execute("SET time_zone = 'UTC'") |
| 32 | + |
| 33 | + |
| 34 | +def execute_queries_with_failover_handling(conn: Connection, sql: str, params: Optional[Union[Dict, Tuple]] = None): |
| 35 | + try: |
| 36 | + cursor = conn.cursor() |
| 37 | + cursor.execute(sql, params) |
| 38 | + return cursor |
| 39 | + |
| 40 | + except FailoverSuccessError: |
| 41 | + # Query execution failed and AWS Advanced Python Driver successfully failed over to an available instance. |
| 42 | + # https://github.com/aws/aws-advanced-python-wrapper/blob/main/docs/using-the-python-driver/using-plugins/UsingTheFailoverPlugin.md#failoversuccesserror |
| 43 | + |
| 44 | + # The old cursor is no longer reusable and the application needs to reconfigure sessions states. |
| 45 | + configure_initial_session_states(conn) |
| 46 | + # Retry query |
| 47 | + cursor = conn.cursor() |
| 48 | + cursor.execute(sql) |
| 49 | + return cursor |
| 50 | + |
| 51 | + except FailoverFailedError as e: |
| 52 | + # User application should open a new connection, check the results of the failed transaction and re-run it if needed. See: |
| 53 | + # https://github.com/aws/aws-advanced-python-wrapper/blob/main/docs/using-the-python-driver/using-plugins/UsingTheFailoverPlugin.md#failoverfailederror |
| 54 | + raise e |
| 55 | + |
| 56 | + except TransactionResolutionUnknownError as e: |
| 57 | + # User application should check the status of the failed transaction and restart it if needed. See: |
| 58 | + # https://github.com/aws/aws-advanced-python-wrapper/blob/main/docs/using-the-python-driver/using-plugins/UsingTheFailoverPlugin.md#transactionresolutionunknownerror |
| 59 | + raise e |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == "__main__": |
| 63 | + params = { |
| 64 | + "host": "rds-proxy-name.proxy-xyz.us-east-1.rds.amazonaws.com", |
| 65 | + "database": "mysql", |
| 66 | + "user": "admin", |
| 67 | + "password": "pwd", |
| 68 | + "plugins": "srw,failover", |
| 69 | + "srw_write_endpoint": "rds-proxy-name.proxy-xyz.us-east-1.rds.amazonaws.com", # Replace with write endpoint |
| 70 | + "srw_read_endpoint": "rds-proxy-name-read-only.endpoint.proxy-xyz.us-east-1.rds.amazonaws.com", # Replace with read endpoint |
| 71 | + "srw_verify_new_connections": "True", # Enables role-verification for new endpoints |
| 72 | + "wrapper_dialect": "aurora-mysql", |
| 73 | + "autocommit": True, |
| 74 | + } |
| 75 | + |
| 76 | + """ Setup step: open connection and create tables """ |
| 77 | + with AwsWrapperConnection.connect(mysql.connector.Connect, **params) as conn: |
| 78 | + configure_initial_session_states(conn) |
| 79 | + execute_queries_with_failover_handling( |
| 80 | + conn, |
| 81 | + "CREATE TABLE IF NOT EXISTS bank_test (id int primary key, name varchar(40), account_balance int)", |
| 82 | + ) |
| 83 | + execute_queries_with_failover_handling( |
| 84 | + conn, "INSERT INTO bank_test VALUES (%s, %s, %s)", (0, "Jane Doe", 200) |
| 85 | + ) |
| 86 | + execute_queries_with_failover_handling( |
| 87 | + conn, "INSERT INTO bank_test VALUES (%s, %s, %s)", (1, "John Smith", 200) |
| 88 | + ) |
| 89 | + |
| 90 | + """ Example step: open connection and perform transaction """ |
| 91 | + try: |
| 92 | + with AwsWrapperConnection.connect(mysql.connector.Connect, **params) as conn, conn.cursor() as cursor: |
| 93 | + configure_initial_session_states(conn) |
| 94 | + |
| 95 | + execute_queries_with_failover_handling( |
| 96 | + conn, |
| 97 | + "UPDATE bank_test SET account_balance=account_balance - 100 WHERE name=%s", |
| 98 | + ("Jane Doe",), |
| 99 | + ) |
| 100 | + execute_queries_with_failover_handling( |
| 101 | + conn, |
| 102 | + "UPDATE bank_test SET account_balance=account_balance + 100 WHERE name=%s", |
| 103 | + ("John Smith",), |
| 104 | + ) |
| 105 | + |
| 106 | + # Internally switch to a reader connection |
| 107 | + conn.read_only = True |
| 108 | + for i in range(2): |
| 109 | + cursor = execute_queries_with_failover_handling( |
| 110 | + conn, "SELECT * FROM bank_test WHERE id = %s", (i,) |
| 111 | + ) |
| 112 | + for record in cursor: |
| 113 | + print(record) |
| 114 | + |
| 115 | + finally: |
| 116 | + with AwsWrapperConnection.connect(mysql.connector.Connect, **params) as conn: |
| 117 | + execute_queries_with_failover_handling(conn, "DROP TABLE bank_test") |
0 commit comments